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 allselect '2009年2月第一期','湖州宝吉',92 union allselect '2009年3月第一期','海宁旅行者',90 union allselect '2009年3月第一期','湖州宝吉',80 union allselect '2009年4月第一期','湖州宝吉',96godeclare @sql varchar(8000)set @sql='select col1=left(col1,7)'select @[email protected]+',['+col2+']=sum(case col2 when '''+col2+''' then col3 else 0 end)'from (select distinct col2 from s)aset @[email protected]+' from s group by left(col1,7)'exec(@sql)
------解决方案--------------------
- SQL code
--哦,看错了。直接这样就可以了declare @sql varchar(8000)set @sql='select col1'select @[email protected]+',['+col2+']=sum(case col2 when '''+col2+''' then col3 else 0 end)'from (select distinct col2 from s)aset @[email protected]+' 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