【问题标题】:How to group many rows into one row by Sql Server [duplicate]如何通过Sql Server将多行分组为一行[重复]
【发布时间】:2012-12-17 23:48:33
【问题描述】:

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

我有 2 个这样的表

类表:

还有学生桌:

我想加入两个表,但我想得到这样的结果
ClsName 标准名称
一个       乔治
B           Jenifer,Anjel,Alex
C           亚历克斯、乔、迈克尔


如何做到这一点?
实际上,对于每个班级,我都希望有一排有不同的学生姓名

【问题讨论】:

标签: sql-server grouping


【解决方案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

【讨论】:

  • 您可能希望将其设为 ','+name,然后将其设为 STUFF 以删除第一个字符,这样它就不会以逗号结尾。
【解决方案2】:

您应该能够使用以下内容:

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2021-12-08
  • 1970-01-01
  • 1970-01-01
  • 2015-07-28
  • 2014-02-26
  • 2020-11-14
  • 2019-09-25
  • 1970-01-01
相关资源
最近更新 更多