日期:2014-05-17  浏览次数:20531 次

SQL SERVER 2008行转列问题
如图,这是直接select * from tushu 得到的结果。我想要显示的结果是这样的:

中华护理   1—6月  骨一科,骨二科,骨三科,外一科
中华护理   6—12月  外二科,信息科,院办,党办,宣传科
中华护理   1—12月  医教科,脑病科、医保办、脾胃病科、
读者       6—12月  脑科、肺病科、内科
读者      1—12月  书记1、书记2、院长1、院长2、院长3

怎么写SQL语句,谢谢大家。

------解决方案--------------------
try this,

select a.书刊,a.起止日期,
       stuff((select ','+b.订阅科室
              from tushu b
              where b.书刊=a.书刊 and b.起止日期=a.起止日期
              for xml path('')),1,1,'') '订阅科室'
 from tushu a
 group by a.书刊,a.起止日期

------解决方案--------------------

use [TestDB]
go
if object_id('tempdb..#t') is not null
drop table #t;

select N'中华护理' [书刊],N'1—6月' [起止日期],N'骨一科' [订阅科室]
into #t
union all select N'中华护理',N'1—6月',N'骨二科'
union all select N'中华护理',N'1—6月',N'骨三科'
union all select N'中华护理',N'1—6月',N'外一科'
union all select N'中华护理',N'6—12月',N'外二科'
union all select N'中华护理',N'6—12月',N'信息科'
union all select N'中华护理',N'6—12月',N'院办'
union all select N'中华护理',N'6—12月',N'党办'
union all select N'中华护理',N'6—12月',N'宣传科'
union all select N'中华护理',N'1—12月',N'医教科'
union all select N'中华护理',N'1—12月',N'脑病科'
union all select N'中华护理',N'1—12月',N'医保办'
union all select N'中华护理',N'1—12月',N'脾胃病科'
union all select N'读者',N'6—12月',N'脑科'
union all select N'读者',N'6—12月',N'肺病科'
union all select N'读者',N'6—12月',N'内科'
union all select N'读者',N'1—12月',N'书记1'
union all select N'读者',N'1—12月',N'书记2'
union all select N'读者',N'1—12月',N'院长1'
union all select N'读者',N'1—12月',N'院长2'
union all select N'读者',N'1—12月',N'院长3'


select [书刊],[起止日期],
stuff((select ','+[订阅科室] from #t b where a.书刊=b.书刊 and a.起止日期=b.起止日期
for xml path('')
),1,1,'') [订阅科室]
from #t a
group by [书刊],[起止日期]
 order by 1 desc