Skip to content

Instantly share code, notes, and snippets.

@hsinjungwu
Created January 15, 2015 09:06
Show Gist options
  • Select an option

  • Save hsinjungwu/adcbc140926049559620 to your computer and use it in GitHub Desktop.

Select an option

Save hsinjungwu/adcbc140926049559620 to your computer and use it in GitHub Desktop.
An example to Concatenates Values of specified column Group By another column in SQL Server
--REFERENCE:http://stackoverflow.com/a/19348687
DECLARE @table TABLE(idx INT, name VARCHAR(10))
INSERT @table VALUES(0, 'hjwu01')
INSERT @table VALUES(0, 'hjwu02')
INSERT @table VALUES(0, 'hjwu03')
INSERT @table VALUES(1, 'hjwu11')
INSERT @table VALUES(1, 'hjwu12')
INSERT @table VALUES(2, 'hjwu21')
INSERT @table VALUES(2, 'hjwu22')
--want to show as follows
/*
0, 'hjwu01,hjwu02,hjwu03'
1, 'hjwu11,hjwu12'
2, 'hjwu21,hjwu22'
*/
SELECT idx, STUFF
(
(
SELECT ',' + name
FROM @table tA
WHERE tA.idx = tB.idx FOR XML PATH('')
), 1, 1, ''
) AS myname
FROM @table tB
GROUP BY tB.idx
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment