Mam tabelę z dwiema kolumnami MentionedUserIds
(nvarchar
) i CreatedUserId
(int
).
Chcia
Id MentionedUserId CreatorUserId
--------------------------------
1 10,11,12,13 4
2 10,13,15,4 5
Potrzebuję takiego wyniku:
UserId MentionedUserCount CreatorUserCount
-------------------------------------------
4 1 1
5 0 1
10 2 0
11 1 0
12 1 0
13 2 0
15 1 0
Użytkownicy są przechowywani w innej tabeli.
Odpowiedzi:
0 dla odpowiedzi № 1Pytanie jest trywialne po znormalizowaniu danych. Można to zrobić za pomocą dowolnej liczby plików funkcje lub sztuczki.
Z dostępnym wyszukiwaniem pełnotekstowym firmy Microsoft:
With Src As (
Select * From (Values
(1, "10,11,12,13", 4),
(2, "10,13,15,4" , 5)
) V (Id, MentionedUserId, CreatorUserId)
), Normalised As (
Select CreatorUserId, CAST(display_term AS int) As MentionedUserId
From Src
Cross Apply (
Select display_term
From sys.dm_fts_parser(""" + MentionedUserId + """, 1033, 0, 0)
Where display_term NOT Like "nn%"
) Split
), UserList As (
Select CreatorUserId As UserId From Normalised Union
Select MentionedUserId From Normalised
)
Select UserId,
(Select Count(*) From Normalised Where MentionedUserId = UserId) As MentionedUserCount,
(Select Count(*) From Src Where CreatorUserId = UserId) As CreatorUserCount
From UserList;
Poprzez sztuczkę XML:
With Src As (
Select * From (Values
(1, "10,11,12,13", 4),
(2, "10,13,15,4" , 5)
) V (Id, MentionedUserId, CreatorUserId)
), Normalised As (
Select CreatorUserId, y.i.value("(./text())[1]", "int") As MentionedUserId
From Src
Cross Apply (Select CONVERT(XML, "<i>" + REPLACE(MentionedUserId, ",", "</i><i>") + "</i>").query(".") As x) As a
Cross Apply x.nodes("i") As y(i)
), UserList As (
Select CreatorUserId As UserId From Normalised Union
Select MentionedUserId From Normalised
)
Select UserId,
(Select Count(*) From Normalised Where MentionedUserId = UserId) As MentionedUserCount,
(Select Count(*) From Src Where CreatorUserId = UserId) As CreatorUserCount
From UserList;