如何通过Sql Server将多行分组到一行

时间:2013-01-03 15:27:40

标签: sql-server grouping

  

可能重复:
  Simulating group_concat MySQL function in Microsoft SQL Server 2005?

我有2张这样的桌子

班级表:
enter image description here

学生表:
enter image description here

我想加入两张桌子,但我希望得到这样的结果 ClsName StdName
乔治
B Jenifer,Anjel,Alex
C亚历克斯,乔,迈克尔


怎么能达到这个目的?
事实上,对于每个班级,我希望有一行具有不同的学生姓名

2 个答案:

答案 0 :(得分:4)

您应该可以使用以下内容:

select c.name ClassName,
    STUFF(( SELECT  distinct ', ' + s.name
            FROM    student s
            WHERE   c.id = s.classid
            FOR XML PATH('')
            ), 1, 2, '')  Names
from class c

结果:

ClassName | Names
A         | George
B         | Alex, Anjel, Jenifer
C         | Alex, Joe, Micheal

以下是我使用的工作查询:

;with class(id, name) as
(
    select 1, 'A'
    union all
    select 2, 'B'
    union all
    select 3, 'C'
),
student(id, name, classid) as
(
    select 1, 'Alex', 3
    union all
    select 2, 'Alex', 3
    union all
    select 3, 'Alex', 3
    union all
    select 4, 'Joe', 3
    union all
    select 5, 'Micheal', 3
    union all
    select 6, 'Jenifer', 2
    union all
    select 7, 'Anjel', 2
    union all
    select 8, 'Alex', 2
    union all
    select 9, 'George', 1
)
select c.name,
    STUFF(( SELECT  distinct ', ' + s.name
            FROM    student s
            WHERE   c.id = s.classid
            FOR XML PATH('')
            ), 1, 2, '') Names
from class c

答案 1 :(得分:1)

你可以试试这个:

SELECT 
    distinct
    S.Classid,
    (
        SELECT name + ','
        FROM Student S2
        WHERE S2.Classid = S.Classid
        FOR XML PATH('')
    ) StdName,
    C.name ClsName
FROM 
Student S INNER JOIN Class C
ON S.Classid = C.id