Вы можете использовать следующий запрос, используя FOR XML PATH('')
.
create table Student(StudentId int identity(1, 1)
, Name varchar(20)
, code int
, age int
, classId int)
insert into Student values
('Jeremy', 381, 20, 14),
('Jeremy', 381, 20, 5),
('Jeremy', 381, 20, 11),
('Sarah', 920, 23, 20),
('Sarah', 920, 23, 3)
create table StudentClass (classId int
, className varchar(20))
insert into StudentClass values
(3, 'Class A'),
(5, 'Class B'),
(10, 'Class C'),
(11, 'Class D'),
(14, 'Class E'),
(14, 'Class F')
SELECT Name, Code, Age, classId =
STUFF((SELECT ', ' + Cast(classId as varchar(3))
FROM Student b
WHERE b.Name = a.Name
and b.Code = a.Code
and b.age = a.age
FOR XML PATH('')), 1, 2, '')
FROM Student a
GROUP BY Name
, Code
, Age
Live db <> fiddle demo.