[英]SQL group by and cross apply
id | systemName | Systemid
-------------------------------
100 | A100 | 1
100 | B100 | 2
100 | C100 | 3
100 | D100 | 4
200 | A100 | 1
200 | B200 | 2
What is the best way to achieve the below result? 实现以下结果的最佳方法是什么? Column System name should have the comma separated values of counted systems 列系统名称应使用逗号分隔计数系统的值
id Systemidcount SystemName
---------------------------------------------
100 | 4 | A100,B100,C100,D100
200 | 2 | A100,B200
I am not able to format it correctly for some reason, apologies 抱歉,由于某些原因,我无法正确设置其格式
You may notice the sub-query alias A. This is to prevent redundant calls in the CROSS APPLY 您可能会注意到子查询别名A。这是为了防止在CROSS APPLY中进行多余的调用
Declare @YourTable table (id int,systemname varchar(25),systemid int)
Insert Into @YourTable values
(100,'A100',1),
(100,'B100',2),
(100,'C100',3),
(100,'D100',4),
(200,'A100',1),
(200,'B200',2)
Select A.*
,SystemName = B.Value
From (Select ID,Systemidcount = count(*) From @YourTable Group By ID) A
Cross Apply (
Select Value=Stuff((Select Distinct ',' + systemname
From @YourTable
Where ID=A.ID
For XML Path ('')),1,1,'')
) B
Order By ID
Returns 返回
ID Systemidcount SystemName
100 4 A100,B100,C100,D100
200 2 A100,B200
This is string aggregation: 这是字符串聚合:
select id, count(*) as systemidcount,
stuff(v.systemnames, 1, 1, '') as systemnames
from t cross apply
(select ',' + systemName
from t t2
where t2.id = t.id
for xml path ('')
) v(systemnames);
SELECTid,COUNT(Systemid) as SystemidCount,
SystemName=Stuff((SELECT ',' + SystemName FROM t t1 WHERE t1.id=t.id
FOR XML PATH (''))
, 1, 1, '' )
FROM t
GROUP BY id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.