日期:2014-05-17  浏览次数:20422 次

将一个三个字段的表转化为行列表
如何把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 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

*/


------解决方案--------------------
试试看能否
declare @s varchar(max)
set @s=''
select @s=@s+','+quotename(AplOn)+'=sum(case when AplOn='+quotename(AplOn,'''')+' then 1 else 0 end)' from EngineeringMonthReport group by AplOn
set @s='select b.BusinessUnitName AS Name' +@s+'from dbo.EngineeringMonthReport a, dbo.BusinessUnit b
  WHERE
  a.BusinessUnitId = b.BusinessUnitId
  GROUP BY
  b.BusinessUnitName