数据库表students只有班级和姓名两个字段,数据如下班级     姓名
1 张德江
1 黎明
1 钟文
5 刘进
8 陈明明我想把每个班的学生合并起来,用逗号隔开,想要的结果如下:第1班(张德江,黎明,钟文)
第5班(刘进)
第8班(陈明明)请问sql查询代码应该如何写才能得到上面的结果啊?

解决方案 »

  1.   

    if object_id('[TB]') is not null drop table [TB]
    go
    create table [TB] (班级 int,姓名 nvarchar(6))
    insert into [TB]
    select 1,'张德江' union all
    select 1,'黎明' union all
    select 1,'钟文' union all
    select 5,'刘进' union all
    select 8,'陈明明'select '第'+CONVERT(VARCHAR,班级)+'班' AS 班级, [姓名]='('+stuff((select ','+[姓名] from tb t where 班级=tb.班级 for xml path('')), 1, 1, '') +')'
    from tb 
    group by 班级/*
    班级                                 姓名
    ---------------------------------- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
    第1班                                (张德江,黎明,钟文)
    第5班                                (刘进)
    第8班                                (陈明明)(3 行受影响)*/
      

  2.   

    SELECT  case when a.班级='1' then '第1班' when a.班级='5' then '第5班' when a.班级='8' then '第8班' end  班级 ,
               姓名 = STUFF(( SELECT ',' +姓名
                            FROM   students 
                            WHERE  班级= a.班级
                          FOR
                            XML PATH('')
                          ), 1, 1, '')
       FROM    students a
       GROUP BY case when a.班级='1' then '第1班' when a.班级='5' then '第5班' when a.班级='8' then '第8班' end