日期:2014-05-17 浏览次数:20495 次
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 行受影响)*/
------解决方案--------------------
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