我需要一个TSQL版本的group_concat Simmilar对该示例发现了here:
Policy Destination ID
-------------------------
PolA DestA 1
PolA DestA 2
PolB DestB 3
PolB DestB 4
PolC DestC 5
PolC DestC 6
PolC DestD 7
PolA DestA 1,2
PolB DestB 3,4
PolC DestC 5,6
PolC DestD 7
分组是前两列的唯一性,然后是第三列的连接输出。
我找到了this link,但它只考虑了2列
任何帮助都将不胜感激。
答案 0 :(得分:1)
在MSSQL Synax中:
SELECT Policy, Destination, STRING_AGG ( [ID], ',' ) IDs
FROM Table
答案 1 :(得分:1)
你可以试试这个:
SELECT G.Policy, G.Destination,
stuff(
(select cast(',' as varchar(max)) + U.ID
from yourtable U
WHERE U.Policy = G.Policy and U.Destination = G.Destination
order by U.Policy
for xml path('')
), 1, 1, '') AS IDs
FROM yourtable G group BY G.Policy, G.Destination
答案 2 :(得分:0)
我只是为您创建PolA
示例表,只需将CTE替换为您的表格,请尝试以下操作:
WITH ABC
as
(
select 'PolA' as Policy,'DestA' as Destination,'1' as ID
UNION ALL
select 'PolA','DestA','2'
)
SELECT Policy, Destination,
STUFF((SELECT ',' + A.ID FROM ABC as A WHERE A.Policy = B.Policy FOR XML PATH('')),1,1,'') as ID
FROM ABC as B
GROUP BY B.policy, B.Destination