You are on the right track with
STUFF
, and what you need to do is to put that into a
SubQuery
Proof of Concept
DECLARE @table TABLE (ID int, color varchar(16))
INSERT @table VALUES (1, 'black'), ( 1, 'white'), ( 1, 'blue'), ( 2, 'red'), ( 3, 'magenta'), ( 3, 'purple')
SELECT t.ID
, Colors = STUFF(
( SELECT ', ' + s.color
FROM @table s
WHERE s.ID = t.ID
FOR XML PATH('')
), 1, 1, ''
)
FROM @table t
GROUP BY t.ID
ORDER BY 1
Which returns
ID Colors
== ===================
1 black, white, blue
2 red
3 magenta, purple