Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server Convert Particular Column Values into comma separated String

I have a table in Database as below :

Id  Name
1   Item1
1   Item2
2   Item3
1   Item4
3   Item5

I need output as below(3rd column is count):

1   Item1,Item2,Item4   3
2   Item3               1
3   Item5               1

How it can achieved by SQL Query ?

like image 261
Mayank Avatar asked Oct 20 '25 21:10

Mayank


1 Answers

SQL Server has STUFF() function which could able to help you.

SELECT t.Id,
       Name = STUFF( (SELECT DISTINCT ','+Name 
                      FROM table 
                      WHERE Id = t.Id 
                      FOR XML PATH('')
                     ), 1, 1, ''
                   ) 
FROM table t
GROUP BY t.Id; 
like image 110
Yogesh Sharma Avatar answered Oct 22 '25 10:10

Yogesh Sharma



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!