string concatenate in group by function with other aggregate functions

后端 未结 3 1886
旧时难觅i
旧时难觅i 2021-01-05 08:24

Is it possible to concatenate strings with one or more of other group by function like sum, avg, count etc .

Say I have the following table

Id Name O         


        
3条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-05 08:57

    Sample table

    create table t123 (Id int, Name varchar(10), [Order] int, Value int)
    insert t123 select 
    1,'a','1',100 union all select
    2,'b','2',200 union all select
    3,'c','1',300 union all select
    4,'d','1',100 union all select
    5,'e','2',300
    

    Query for SQL Server 2005 and above

    select a.[order], STUFF((
        select ','+b.name
        from t123 b
        where b.[order] = a.[order]
        order by b.name
        for xml path('a'), type).value('.','nvarchar(max)'),1,1,'') Name,
        SUM(a.value) value,
        COUNT(*) [count]
    from t123 a
    group by a.[order]
    

    Output

    order       Name         value       count
    ----------- ------------ ----------- -----------
    1           a,c,d        500         3
    2           b,e          500         2
    

提交回复
热议问题