测试数据
DECLARE @TABLE TABLE (StudentIdId INT, Name VARCHAR(100), University VARCHAR(100)
, Department VARCHAR(100),[Status] VARCHAR(100))
INSERT INTO @TABLE VALUES
(1 ,'John','Cambridge','Computer' ,'Graduated'),
(1 ,'John','Berkeley' ,'Mathematic','Graduated'),
(1 ,'John','Boston' ,'Economy' ,'Ongoing'),
(2 ,'Pete','Cambridge','Computer' ,'Graduated'),
(2 ,'Pete','Berkeley' ,'Mathematic','Graduated')
询问
SELECT t.StudentIdId
,t.Name
,STUFF((SELECT ', ' + University
FROM @TABLE
WHERE StudentIdId = t.StudentIdId
FOR XML PATH(''),TYPE).value('.','NVARCHAR(MAX)'),1,2,'') AS University
,STUFF((SELECT ', ' + Department
FROM @TABLE
WHERE StudentIdId = t.StudentIdId
FOR XML PATH(''),TYPE).value('.','NVARCHAR(MAX)'),1,2,'') AS Department
,STUFF((SELECT ', ' + [Status]
FROM @TABLE
WHERE StudentIdId = t.StudentIdId
FOR XML PATH(''),TYPE).value('.','NVARCHAR(MAX)'),1,2,'') AS [Status]
FROM @TABLE t
GROUP BY t.StudentIdId ,t.Name
结果
╔═════════════╦══════╦═════════════════════════════╦═══════════════════════════════╦═══════════════════════════════╗
║ StudentIdId ║ Name ║ University ║ Department ║ Status ║
╠═════════════╬══════╬═════════════════════════════╬═══════════════════════════════╬═══════════════════════════════╣
║ 1 ║ John ║ Cambridge, Berkeley, Boston ║ Computer, Mathematic, Economy ║ Graduated, Graduated, Ongoing ║
║ 2 ║ Pete ║ Cambridge, Berkeley ║ Computer, Mathematic ║ Graduated, Graduated ║
╚═════════════╩══════╩═════════════════════════════╩═══════════════════════════════╩═══════════════════════════════╝