以下を使用できるはずです。
select c.name ClassName,
STUFF(( SELECT distinct ', ' + s.name
FROM student s
WHERE c.id = s.classid
FOR XML PATH('')
), 1, 2, '') Names
from class c
結果:
ClassName | Names
A | George
B | Alex, Anjel, Jenifer
C | Alex, Joe, Micheal
私が使用した作業クエリは次のとおりです。
;with class(id, name) as
(
select 1, 'A'
union all
select 2, 'B'
union all
select 3, 'C'
),
student(id, name, classid) as
(
select 1, 'Alex', 3
union all
select 2, 'Alex', 3
union all
select 3, 'Alex', 3
union all
select 4, 'Joe', 3
union all
select 5, 'Micheal', 3
union all
select 6, 'Jenifer', 2
union all
select 7, 'Anjel', 2
union all
select 8, 'Alex', 2
union all
select 9, 'George', 1
)
select c.name,
STUFF(( SELECT distinct ', ' + s.name
FROM student s
WHERE c.id = s.classid
FOR XML PATH('')
), 1, 2, '') Names
from class c