加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

sql – string按功能与其他聚合函数连接

发布时间:2020-12-12 06:53:49 所属栏目:MsSql教程 来源:网络整理
导读:是否可以通过函数(如sum,avg,count等)将字符串与一个或多个其他组连接起来. 说我有下表 Id Name Order Value 1 a 1 100 2 b 2 200 3 c 1 300 4 d 1 100 5 e 2 300 现在,如果我希望结果是这种类型的东西 Order Name Value Count 1 a,c,d 500 3 2 b,e 500 2 如
是否可以通过函数(如sum,avg,count等)将字符串与一个或多个其他组连接起来.

说我有下表

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

现在,如果我希望结果是这种类型的东西

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

如何在SQL服务器上使用查询来实现相同的功能.

解决方法

样本表
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',300 union all select
4,'d',100 union all select
5,'e',300

查询SQL Server 2005及更高版本

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,'') Name,SUM(a.value) value,COUNT(*) [count]
from t123 a
group by a.[order]

产量

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读