日期:2014-05-18  浏览次数:20512 次

行列转换 急!
Col1 Col2 Col3
2009年2月第一期 海宁旅行者 100
2009年2月第一期 湖州宝吉 92
2009年3月第一期 海宁旅行者 90
2009年3月第一期 湖州宝吉 80
2009年4月第一期 湖州宝吉 96

把上面的数据格式变成下面的格式,

Col1 海宁旅行者 湖州宝吉
2009年2月第一期 100 92
2009年3月第一期 90 80
2009年4月第一期 null 96

谢谢!



------解决方案--------------------
SQL code
--> 测试数据: [s]
if object_id('[s]') is not null drop table [s]
create table [s] (Col1 varchar(15),Col2 varchar(10),Col3 int)
insert into [s]
select '2009年2月第一期','海宁旅行者',100 union all
select '2009年2月第一期','湖州宝吉',92 union all
select '2009年3月第一期','海宁旅行者',90 union all
select '2009年3月第一期','湖州宝吉',80 union all
select '2009年4月第一期','湖州宝吉',96
go

declare @sql varchar(8000)
set @sql='select col1=left(col1,7)'
select @sql=@sql+',['+col2+']=sum(case col2 when '''+col2+''' then col3 else 0 end)'
from (select distinct col2 from s)a
set @sql=@sql+' from s group by left(col1,7)'
exec(@sql)

------解决方案--------------------
SQL code

--哦,看错了。直接这样就可以了

declare @sql varchar(8000)
set @sql='select col1'
select @sql=@sql+',['+col2+']=sum(case col2 when '''+col2+''' then col3 else 0 end)'
from (select distinct col2 from s)a
set @sql=@sql+' from s group by col1'
exec(@sql)

------解决方案--------------------
SQL code
select col1,
       sum(case when col2='海宁旅行者' then col3 else 0 end)[海宁旅行者],
       sum(case when col2=' 湖州宝吉' then col3 else 0 end)[ 湖州宝吉]
 from tb group by col1