-1
with cte (PersonID, FirstName, name) 
as
(
    select 
        p.PersonID, p.FirstName, dep.name 
    from 
        [PersonDepMapping] map 
    inner join 
        person p on map.personid = p.PersonID
    inner join 
        Department dep on dep.DepartmentID = map.DepartmentID
)
select * 
from cte

This is what I am getting now:

1   Kim     English
1   Kim     Economics
2   Gytis   Engineering
3   Peggy   Mathematics

I want an output something like this:

1   Kim     English, Economics
2   Gytis   Engineering
3   Peggy   Mathematics

Can anyone please help? I couldn't find any answer that could help me get what I need - do I need to use GROUP BY or FOR XML PATH or something else entirely?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
devloper
  • 41
  • 1
  • 7
  • 1
    Does this answer your question? [Optimal way to concatenate/aggregate strings](https://stackoverflow.com/questions/13639262/optimal-way-to-concatenate-aggregate-strings) – Amit Verma Aug 21 '21 at 10:49

1 Answers1

2

You are looking for string_agg() (available since SQL Server 2017):

select p.PersonID, p.FirstName,
       string_agg(dep.name, ',')
from PersonDepMapping map inner join
     person p
     on map.personid = p.PersonID join
     Department dep
     on dep.DepartmentID = map.DepartmentID
group by p.PersonID, p.FirstName;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786