2015-05-21 45 views
-1

我有這樣SQL Server組通過與集團的毗連

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 
+0

你得到了什麼錯誤? – tharif

+0

該查詢工作正常,期望我希望不同的醫院 –

+0

在您的輸出之後發佈您期望的輸出 – tharif

回答

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; 
+0

這也會起作用 –

+0

您是我的英雄,非常感謝 –

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 
+0

計數處於關閉狀態。期待4 – TTeeple

+0

非常感謝t-clausen.dk –