日期:2014-05-17 浏览次数:20553 次
create table #tb(cmonth int,CompanyName varchar(50),amt int)
insert into #tb
select 1,'公司A',100
union all select 2,'公司A',400
union all select 3,'公司A',500
union all select 5,'公司A',400
union all select 7,'公司B',200
union all select 3,'公司B',200
union all select 4,'公司B',200
union all select 5,'公司C',200
union all select 6,'公司C',200
union all select 7,'公司C',200
union all select 8,'公司D',200
union all select 9,'公司D',800
union all select 10,'公司D',900
union all select 11,'公司D',1100
union all select 12,'公司D',1200
declare @sql varchar(8000)
set @sql=''
select @sql=@sql + ',['+rtrim(cmonth)+']=sum(case cmonth when '''+rtrim(cmonth)+''' then amt else 0 end)'
from #tb group by cmonth
exec('select CompanyName'+@sql+'from #tb group by CompanyName' )
go
/*
CompanyName 1 2 3 4 5 6 7 8 9 10 11 12
-------------------------------------------------------------------------
公司A 100 400 500 0 400 0 0 0 0 0 0 0
公司B 0 0 200 200 0 0 200 0 0 0 0 0
公司C 0 0 0 0 200 200 200 0 0 0 0 0
公司D 0 0 0 0 0 0 0 200 800 900 1100 1200
*/