Monday, August 31, 2020

How to create a comma separated list with group by in SQL SERVER

Say you have a table t with following values and you need comma separated name group by ID

ID    Name

1 A

2 B

3 C

4 D

4 E


SELECT ID, STRING_AGG(Name, ', ') AS Names

FROM (

select ID, Name from t)s

GROUP BY ID


This will give the following result:

ID     Names

1 A

2 B

3 C

4 D, E


No comments: