Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server - join rows into comma separated list

Tags:

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.

like image 798
Bogdan Pușcașu Avatar asked Jul 05 '17 06:07

Bogdan Pușcașu


People also ask

How do I combine rows and commas in SQL?

You can concatenate rows into single string using COALESCE method. This COALESCE method can be used in SQL Server version 2008 and higher. All you have to do is, declare a varchar variable and inside the coalesce, concat the variable with comma and the column, then assign the COALESCE to the variable.

How do you join rows in SQL?

SQL JOIN. A JOIN clause is used to combine rows from two or more tables, based on a related column between them. Notice that the "CustomerID" column in the "Orders" table refers to the "CustomerID" in the "Customers" table. The relationship between the two tables above is the "CustomerID" column.


1 Answers

You are missing the condition inside the sub query.

SELECT t2.Id, STUFF((SELECT ',' + CAST(VALUE AS varchar) FROM @MyTable t1  where t1.Id =t2.ID FOR XML PATH('')), 1 ,1, '') AS ValueList FROM @MyTable t2 GROUP BY t2.Id 

Demo

like image 110
Shiju Shaji Avatar answered Oct 04 '22 17:10

Shiju Shaji