SQL Server Group By with Group Concat

时间:2015-05-21 12:22:40

标签: sql-server group-by group-concat sql-server-group-concat

我有一张这样的表

Hospital    Insurance   PatientCount
H1          I1          1
H1          I1          2
H2          I1          1
H2          I2          1

想要通过保险将此表分组为

Hospital    Insurance   PatientCount
H1,H2           I1          4
H2              I2          1

尝试使用

select 
stuff((select ', ' + Hospital
from  Insurances 
where (InsuranceName = i.InsuranceName)
for xml path(''),type).value('(./text())[1]','varchar(max)')
  ,1,2,'') as Hospitals,
i.InsuranceName,
sum(i.PatientsCount)
from Insurances i
group by i.InsuranceName;

输出:

Hospital    Insurance   PatientCount
H1,H1,H2        I1          4
H2              I2          1

2 个答案:

答案 0 :(得分:1)

只需将DISTINCT添加到STUFF

select 
stuff((select DISTINCT ', ' + Hospital
from  A 
where (InsuranceName = i.InsuranceName)
for xml path(''),type).value('(./text())[1]','varchar(max)')
  ,1,2,'') as Hospitals,
i.InsuranceName,
sum(i.PatientCount)
from A i
group by i.InsuranceName;

答案 1 :(得分:1)

此语法有效:

DECLARE @t table
(Hospital char(2), InsuranceName char(2), PatientCount int)
INSERT @t values
('H1','I1',1),
('H1','I1',2),
('H2','I1',1),
('H2','I2',1)


SELECT 
    STUFF(( 
        SELECT ',' + [Hospital] 
        FROM @t t1 
        WHERE t1.InsuranceName = t.InsuranceName
        GROUP BY  [Hospital] 
        for xml path(''), type
    ).value('.', 'varchar(max)'), 1, 1, '') Hospital,
    InsuranceName, 
    SUM(PatientCount) [Patientcount] 
FROM @t t 
GROUP BY InsuranceName

结果:

Hospital  InsuranceName  Patientcount
H1,H2     I1             3
H2        I2             1