Table is:
+----+------+
| Id | Name |
+----+------+
| 1 | aaa |
| 1 | bbb |
| 1 | ccc |
| 1 | ffffd |
| 1 | eee |
+----+------+
SELECT ID,
abc = STUFF(
(SELECT ',' + name FROM temp1 FOR XML PATH ('')), 1, 1, ''
)
FROM temp1 GROUP BY id
Here in the above query STUFF function is used to just remove the first comma (,)
from the generated xml string (,aaa,bbb,ccc,ffffd,eee)
then it will become (aaa,bbb,ccc,ffffd,eee)
.
And FOR XML PATH('')
simply converts column data into (,aaa,bbb,ccc,ffffd,eee)
string but in PATH we are passing '' so it will not create a XML tag.
And at the end we have grouped records using ID column.