sql group by multiple row

时间:2014-02-02 20:31:21

标签: sql sql-server

我有一张这样的桌子:

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  

1 个答案:

答案 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       ║
╚═════════╩══════════╩═══════════════════╝