Concatenate multiple values to a single column using stuff() in SQL

戏子无情 提交于 2019-12-29 09:37:10

问题


ID  | NAME  
----|--------  
1   |Ann  
2   |Jake  
1   |Julie  
3   |Paul  
2   |Shane  
4   |Kumi

I want to concatenate values using stuff() as below. And the single values should not be affected by the stuff() function.

ID  | NAME  
----|--------  
1   |Ann,Julie  
2   |Jake,Shane  
3   |Paul  
4   |Kumi

How to do that?


回答1:


CREATE TABLE #A
(ID INT, NAME VARCHAR(10))
INSERT INTO #A VALUES
(1,'ANN'),
(2,'JAKE'),
(1,'JULIE'),
(3,'PAUL'),
(2,'SHANE'),
(4,'KUMI')

SELECT DISTINCT ID ,
STUFF((SELECT ','+NAME
FROM #A T1
WHERE T1.ID=T2.ID
FOR XML PATH('')),1,1,'') FROM #A T2



回答2:


STUFF doesn't do concatenation,Its for XML which does this.Stuff only replaces values as per choice

select id,
stuff((select ','+name from #t1 t2 where t1.id=t2.id for xml path('')),1,1,'')
from #t1 t1
group by  id


来源:https://stackoverflow.com/questions/38654859/concatenate-multiple-values-to-a-single-column-using-stuff-in-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!