2015-05-21 2 views
-1

У меня есть таблица, как этотSQL Server Group By с групповым 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 
+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 –