string concatenate in group by function with other aggregate functions

后端 未结 3 1910
旧时难觅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 09:09

    Try using this.

    • I placed your original query in a CTE.
    • Then I selected from it, and grouped by the order.
    • Then I cross applied with a subquery that gets a comma-delimited set of names for each order in the outer query.
    • Since I also selected the names column, I had to also group by the names column.

    Like this:

    ;WITH cte(id, n, o, v) as (
       SELECT Id, Name, Order, Value FROM ....
    )
    SELECT o, names, SUM(v), COUNT(*)
    FROM cte AS outer
    CROSS APPLY (
        SELECT Name+',' 
        FROM cte AS inner 
        WHERE outer.o = inner.o 
        ORDER BY Name FOR XML PATH('')
    ) n(names)
    group by o, names
    

提交回复
热议问题