六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 91|回复: 0

逐月对比的交叉表处理

[复制链接]

升级  72.35%

801

主题

801

主题

801

主题

探花

Rank: 6Rank: 6

积分
2447
 楼主| 发表于 2013-2-5 09:05:41 | 显示全部楼层 |阅读模式
/*--原帖地址:
http://community.csdn.net/Expert/topic/3841/3841808.xml?temp=.4308588
--*/
--测试数据
create table tb(year int,month int,No varchar(10),Name varchar(10),部门 varchar(10),工资 int)
insert tb select 2004,10,'A001','AAA','DDD',1000
union all select 2004,10,'B001','BBB','DDD',800
union all select 2004,11,'A001','AAA','DDD',1100
union all select 2004,11,'B001','BBB','DDD',1000
union all select 2004,12,'A001','AAA','DDD',1200
union all select 2004,12,'B001','BBB','DDD',1050
/*--处理要求
将月份做为字段,并且反应逐月的工资增幅,例如上面的数据要求结果如下,注意最小的年月是没有增幅的
No Name 部门 2004_10 2004_11 2004_11增幅 2004_12 2004_12增幅
------ ------ ------ --------- -------- ----------- --------- ------------
A001 AAA DDD 1000 1100 10.00% 1200 9.09%
B001 BBB DDD 800 1000 25.00% 1050 5.00%
--*/
go
--查询处理
declare @s nvarchar(4000),@i int
select @s='',@i=0
select @s=@s+','+quotename(fd)
+'=sum(case when a.year='+year
+' and a.month='+month
+' then a.工资 end)'
+case @i when 0 then ''
else ','+quotename(fd+'增幅')
+'=cast(cast(sum(case when a.year='+year
+' and a.month='+month
+' then a.工资-b.工资 end)*100.'
+'/sum(case when a.year='+year
+' and a.month='+month
+' then b.工资 end)'
+' as decimal(10,2)) as varchar)+''%'''
end,@i=@i+1
from(
select year=rtrim(year),month=rtrim(month),
fd=rtrim(year)+'_'+rtrim(month)
from tb group by year,month)a
exec('select a.No,a.Name,a.部门[email=]'+@s+'[/email]
from tb a
left join tb b on a.No=b.No and a.Name=b.Name and a.部门=b.部门
and a.year=b.year+(b.month)/12
and a.month=b.month%12+1
group by a.No,a.Name,a.部门')
go
--删除测试
drop table tb
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表