将一个三个字段的表转化为行列表
如何把sql查询出来的一个三个字段的表转化为一个字段为列,一个字段为行,最后一个字段作为数据,比如查询出来为月份,公司名,收益三个字段的表,如何把它转化为以月份为行名,公司名为列,收益为数据的一个表,其中没有的数据为0
[解决办法]
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 123456789101112
-------------------------------------------------------------------------
公司A10040050004000000000
公司B002002000020000000
公司C000020020020000000
公司D000000020080090011001200
*/