0

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 ?

Mayank
  • 327
  • 1
  • 8
  • 22

3 Answers3

6

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; 
Yogesh Sharma
  • 49,081
  • 5
  • 23
  • 49
3

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/

gbdavid
  • 1,599
  • 16
  • 34
0
select id, group_concat(name) csv,
from Table
group by id
Leonid Usov
  • 1,400
  • 11
  • 15