Table: Subject_Selection
Subject Semester Attendee
---------------------------------
ITB001 1 John
ITB001 1 Bob
ITB001 1 Mickey
ITB001 2 Jenny
ITB001 2 James
MKB114 1 John
MKB114 1 Erica
我怎么能得到一个结果的查询:
Subject Semester Attendee
---------------------------------
ITB001 1 John,Bob,Mickey
ITB001 2 Jenny,James
MKB114 1 John,Erica
答案 0 :(得分:2)
测试数据
DECLARE @TABLE TABLE ([Subject] VARCHAR(20),Semester INT,Attendee VARCHAR(20))
INSERT INTO @TABLE VALUES
('ITB001',1,'John'),('ITB001',1,'Bob'),('ITB001',1,'Mickey'),('ITB001',2,'Jenny')
,('ITB001',2,'James'),('MKB114',1,'John'),('MKB114',1,'Erica')
<强>查询强>
SELECT [Subject]
, Semester
, STUFF((SELECT ', ' + Attendee [text()]
FROM @TABLE
WHERE Semester = T.Semester
AND [Subject] = T.[Subject]
FOR XML PATH('')), 1, 2, '') AS Attendee
FROM @TABLE T
GROUP BY [Subject], Semester
Subject
是sql server中使用[] square brackets
的保留字
结果集
╔═════════╦══════════╦═══════════════════╗
║ Subject ║ Semester ║ Attendee ║
╠═════════╬══════════╬═══════════════════╣
║ ITB001 ║ 1 ║ John, Bob, Mickey ║
║ ITB001 ║ 2 ║ Jenny, James ║
║ MKB114 ║ 1 ║ John, Erica ║
╚═════════╩══════════╩═══════════════════╝