字符串按功能与其他聚合功能分组 [英] string concatenate in group by function with other aggregate functions

查看:84
本文介绍了字符串按功能与其他聚合功能分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以按功能将字符串与其他组中的一个或多个连接起来,例如求和,平均,计数等。

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

说我有下表

Id Name Order Value  
1  a    1     100  
2  b    2     200  
3  c    1     300  
4  d    1     100  
5  e    2     300

现在,如果我想要结果变成这样的东西

Now if I want the result to be something of this sort

Order Name   Value Count  
1     a,c,d  500   3  
2     b,e    500   2  

如何在SQL Server上使用查询来实现相同的目的。

How can i achieve the same using a query on SQL server.

推荐答案

样本表

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

Quer对于SQL Server 2005及更高版本,为y

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]

输出

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

这篇关于字符串按功能与其他聚合功能分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆