SQL Server - join rows into comma separated list

Viewed 35645

Let's suppose I have a temporary table which looks like this:

+----+------+
| Id | Value|
+----+------+    
| 1  |   1  |
| 1  |   2  |
| 1  |   3  |
| 2  |   1  |
| 2  |   2  |
+----+------+

And I want my table to be like this:

    +----+----------+
    | Id | ValueList|
    +----+----------+    
    | 1  |   1,2,3  |
    | 2  |   1,2    | 
    +----+----------+

So basically I need to group my values as a comma separated list. I already tried the following:

SELECT Id, STUFF((SELECT ',' + CAST(VALUE AS varchar) FROM @MyTable FOR XML PATH('')), 1 ,1, '') AS ValueList
FROM @MyTable
GROUP BY Id

But I get something like:

        +----+---------------------+
        | Id |      ValueList      |
        +----+---------------------+    
        | 1  |   1,1,1,1,1,1,...   |
        +----+---------------------+

I cant find what I am doing wrong. Could someone help with this query? Or point me to a right direction? Thank you.

5 Answers

One can also combine a FOR XML with a CROSS APPLY (or an OUTER APPLY) for this.

Example snippet:

declare @T table (id int, value int);
insert into @T values (1,1),(1,2),(1,3),(2,1),(2,2);

select id, stuff(x.list,1,1,'') as list
from (select distinct id from @T) as t
cross apply (
 select concat(',',t2.value)
 from @T t2
 where t2.id = t.id 
 for xml path('')
) x(list)
order by id;

Result:

id  list
--  -----
1   1,2,3
2   1,2

And starting from MS Sql Server 2017, STRING_AGG can be used instead.

select id, string_agg(value,',') as list
from Yourtable t
group by id;

Simple Solution

SELECT Id, GROUP_CONCAT(Value) as ValueList FROM MyTable GROUP BY Id;

add distinct to values if required

SELECT Id, GROUP_CONCAT(DISTINCT Value) as ValueList FROM MyTable GROUP BY Id;
Related