一个经典的行转列解决方法

问题的描述是这样的


表A:工作年月,部门,工资,工资附加,三金,固定成本,非固定成本,管理费,成本小计,收入,税金,盈亏

输入结果:
项目             部门1         部门2         部门3         部门4              小计
               本月/本年      本月/本年     本月/本年     本月/本年        本月/本年
工资           100/300         100/300       ....
工资附加       ...
三金           ...
固定成本       ...
非固定成本     ...
管理费         ...
成本小计       ...
收入           ...
税金           ...
盈亏           ...

如何生成这张表



我是这样解决的,通过两层循环,生成sql语句,并执行,代码如下


create table 表A
(工作年月 datetime,
部门 varchar(20),
工资 money,
工资附加 money,
三金 money,
固定成本 money,
非固定成本 money,
管理费 money,
成本小计 money,
收入 money,
税金 money,
盈亏 money
)

insert into 表A select '2006-1-1','部门1', 1,1,1,1,1,1,1,1,1,1
insert into 表A select '2006-5-1','部门1', 1,1,1,1,1,1,1,1,1,1
insert into 表A select '2006-1-1','部门2', 1,1,1,1,1,1,1,1,1,1
insert into 表A select '2006-5-1','部门2', 1,1,1,1,1,1,1,1,1,1
insert into 表A select '2006-1-1','部门3', 1,1,1,1,1,1,1,1,1,1
insert into 表A select '2006-5-1','部门3', 1,1,1,1,1,1,1,1,1,1
insert into 表A select '2006-1-1','部门4', 1,1,1,1,1,1,1,1,1,1
insert into 表A select '2006-5-1','部门4', 1,1,1,1,1,1,1,1,1,1
insert into 表A select '2005-12-1','部门4', 1,1,1,1,1,1,1,1,1,1

declare @sql varchar(8000)
declare @t varchar(8000)
declare @type varchar(50)

declare cur_type cursor for
select * from (select '工资' 项目 union
select '工资附加' union
select '三金' union
select '固定成本' union
select '非固定成本' union
select '管理费' union
select '成本小计' union
select '收入' union
select '税金' union
select '盈亏') b

select @sql=''
open cur_type
fetch next from cur_type into @type
while @@FETCH_STATUS = 0
begin

select @t='''' + @type + ''''
select @t=@t+',cast(sum(case when 部门=''' +a.部门+ ''' and datediff(month, 工作年月, getdate())=0 then ' +@type+ ' else 0 end) as varchar(10))' + a.部门 +'本月'
---  cast(sum(case when 部门='''+a.部门+''' and datediff(year, 工作年月, getdate())=0 then ' +@type+ ' else 0 end) as varchar(10)) ' + a.部门 +'本月本年'
from
(select distinct(部门) 部门 from 表A) a
select @t=@t+',cast(sum(case when datediff(month, 工作年月, getdate())=0 then ' +@type+ ' else 0 end) as varchar(10)) 小计'
select @t = ' select ' + @t + ' from 表A'
select @sql=@sql+@t+' union'
fetch next from cur_type into @type
end
close cur_type
deallocate cur_type
select @sql=left(@sql,len(@sql)-6)
exec (@sql)

drop table 表A

/*
     部门1本月 部门2本月 部门3本月 部门4本月 小计
成本小计 1.00 1.00 1.00 1.00 4.00 
非固定成本1.00 1.00 1.00 1.00 4.00 
工资 1.00 1.00 1.00 1.00 4.00 
工资附加 1.00 1.00 1.00 1.00 4.00 
固定成本 1.00 1.00 1.00 1.00 4.00 
管理费 1.00 1.00 1.00 1.00 4.00 
三金 1.00 1.00 1.00 1.00 4.00 
收入 1.00 1.00 1.00 1.00 4.00 
税金 1.00 1.00 1.00 1.00 4.00 
盈亏 1.00 1.00 1.00 1.00 4.00 
*/




代码不怎么简练,仅作抛砖引玉之用,欢迎大家和我讨论
原文地址:https://www.cnblogs.com/oop/p/410202.html