Search code examples
sql-servergroup-bygroup-concatsql-server-group-concat

SQL Server Group By with Group Concat


I have a table like this

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

Want to group this table by insurance as,

Hospital    Insurance   PatientCount
H1,H2           I1          4
H2              I2          1

Tried using

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;

Output :

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

Solution

  • Just needed to add DISTINCT to the 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;