Summarize the list into a comma-separated string

2020-02-06 16:46发布

问题:

This is the current result that can be changed from day to day

    (int)   (nvarchar)
    Number   Grade
    --------------
         1       a
         1       c
         2       a
         2       b
         2       c
         3       b
         3       a

What I need help is to achieve this result below.

Number      Grade
-----------------
     1       a, c
     2    a, b, c
     3       b, a

回答1:

Use:

declare @t table(Number int, Grade varchar)

insert @t values(1, 'a'), (1, 'c'), (2, 'a'), (2, 'b'), (2, 'c'),
(3, 'b'), (3, 'a')

select t1.Number
    , stuff((
        select ',' + Grade
        from @t t2
        where t2.Number = t1.Number
        for xml path(''), type
    ).value('.', 'varchar(max)'), 1, 1, '') [values]
from @t t1
group by t1.Number


回答2:

Obviously you'll need to replace dbo.tablename with your actual table. Also I'm assuming you're using SQL Server 2005 or better - always useful to specify.

SELECT Number, Grades = STUFF((
    SELECT ', ' + Grade FROM dbo.tablename
    WHERE Number = x.Number 
    FOR XML PATH(''), TYPE).value('.[1]', 'nvarchar(max)'), 1, 2, '')
FROM dbo.tablename AS x
GROUP BY Number;

In SQL Server 2017 and Azure SQL Database, you can use the new aggregation function STRING_AGG(), which is a lot tidier in this case:

SELECT Number, Grades = STRING_AGG(Grade,',')
  FROM dbo.tablename
  GROUP BY Number;