Mayank
Mayank

Reputation: 407

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 ?

Upvotes: 3

Views: 31774

Answers (2)

gbdavid
gbdavid

Reputation: 1749

SQL Server 2017 has introduced a much easier way to achieve this using STRING_AGG(expression, separator).

Here's an example:

SELECT STRING_AGG(T.Name, ', ') FROM MyTable T where MyColumnID = 78

You could even play around with formatting in other ways like this one:

SELECT STRING_AGG(CONCAT(T.MyColumnID,' - ',T.Name), ', ') FROM MyTable T where MyColumnID = 78

More info in this blog I found about it: https://database.guide/the-sql-server-equivalent-to-group_concat/

Upvotes: 9

Yogesh Sharma
Yogesh Sharma

Reputation: 50163

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; 

Upvotes: 12

Related Questions