-1

我有一张这样的桌子

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
4

2 回答 2

1

只需要添加DISTINCTSTUFF.

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;
于 2015-05-21T12:32:23.587 回答
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
于 2015-05-21T12:44:41.787 回答