SQL查询组合行而不使用按功能分组

时间:2015-12-01 06:31:23

标签: sql-server

您好我需要查询此sql示例。请帮助我 enter image description here

1 个答案:

答案 0 :(得分:1)

在SqlServer中,您可以使用FOR XML PATH和STUFF函数来实现此目的:

DECLARE @Test TABLE
  (
     Course  VARCHAR(10),
     Student VARCHAR(10)
  )

INSERT @Test
       (Course,
        Student)
VALUES ('A1',
        'S1'),
       ('A1',
        'S2'),
       ('A1',
        'S3'),
       ('A2',
        'S4'),
       ('A2',
        'S5')

SELECT DISTINCT Course,
                Stuff((SELECT ',' + Student
                       FROM   @Test T1
                       WHERE  T1.Course = T2.Course
                       FOR XML PATH('')), 1, 1, '')
FROM   @Test T2