简体   繁体   中英

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 ?

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; 
select id, group_concat(name) csv,
from Table
group by id

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM