在实现连接多行的XML PATH方法时,我再次遇到麻烦。
给出以下SQL Server temptable
:
project | NAME | display_name
-----------+------------+-------------------
a Developer Amelia
a Developer Ruby
a Administrator Olivia
b User Isla
b Developer Emily
c User Poppy
c Administrator Ava
c Administrator James
结果应为:
project | NAME | display_name
-----------+----------------+----------------
a Developer Amelia, Ruby
Administrator Olivia
b User Isla
Developer Emily
c User Poppy
Administrator Ava,James
使用XML PATH等是否还可以做到这一点?
答案 0 :(得分:1)
是的,您可以使用FOR XML PATH()
子句:
SELECT DISTINCT t.project, t.name, STUFF(t1.display_name, 1, 1, '') AS display_name
FROM table t CROSS APPLY
(SELECT ', '+t1.display_name
FROM table t1
WHERE t1.project = t.project AND t1.name = t.name
FOR XML PATH('')
) t1(display_name);