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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With