34,837
社区成员




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
--哦,看错了。直接这样就可以了
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)
--> 测试数据: [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)