ehxz 发表于 2007-2-5 16:07:35

逐月对比的交叉表处理

<p>将月份做为字段名,并且反映逐月增幅的交叉表处理</p><p><br />/*--原帖地址:<br /><a href="http://community&#46;csdn&#46;net/Expert/topic/3841/3841808&#46;xml?temp=&#46;4308588">http://community&#46;csdn&#46;net/Expert/topic/3841/3841808&#46;xml?temp=&#46;4308588</a><br />--*/</p><p>--测试数据<br />create table tb(year int,month int,No varchar(10),Name varchar(10),部门 varchar(10),工资 int)<br />insert tb select 2004,10,'A001','AAA','DDD',1000<br />union all select 2004,10,'B001','BBB','DDD',800<br />union all select 2004,11,'A001','AAA','DDD',1100<br />union all select 2004,11,'B001','BBB','DDD',1000<br />union all select 2004,12,'A001','AAA','DDD',1200<br />union all select 2004,12,'B001','BBB','DDD',1050</p><p>/*--处理要求</p><p>将月份做为字段,并且反应逐月的工资增幅,例如上面的数据要求结果如下,注意最小的年月是没有增幅的</p><p>No Name 部门 2004_10 2004_11 2004_11增幅 2004_12 2004_12增幅 <br />------ ------ ------ --------- -------- ----------- --------- ------------<br />A001 AAA DDD 1000 1100 10&#46;00% 1200 9&#46;09%<br />B001 BBB DDD 800 1000 25&#46;00% 1050 5&#46;00%<br />--*/</p><p>go</p><p>--查询处理<br />declare @s nvarchar(4000),@i int<br />select @s='',@i=0<br />select @s=@s+','+quotename(fd)<br /> +'=sum(case when a&#46;year='+year<br /> +' and a&#46;month='+month<br /> +' then a&#46;工资 end)'<br />+case @i when 0 then ''<br /> else ','+quotename(fd+'增幅')<br /> +'=cast(cast(sum(case when a&#46;year='+year<br /> +' and a&#46;month='+month<br /> +' then a&#46;工资-b&#46;工资 end)*100&#46;'<br /> +'/sum(case when a&#46;year='+year<br /> +' and a&#46;month='+month<br /> +' then b&#46;工资 end)'<br /> +' as decimal(10,2)) as varchar)+''%'''<br />end,@i=@i+1<br />from(<br />select year=rtrim(year),month=rtrim(month),<br /> fd=rtrim(year)+'_'+rtrim(month)<br />from tb group by year,month)a <br />exec('select a&#46;No,a&#46;Name,a&#46;部门<a href="mailto:'+@s+'">'+@s+'</a><br />from tb a<br />left join tb b on a&#46;No=b&#46;No and a&#46;Name=b&#46;Name and a&#46;部门=b&#46;部门<br /> and a&#46;year=b&#46;year+(b&#46;month)/12<br /> and a&#46;month=b&#46;month%12+1<br />group by a&#46;No,a&#46;Name,a&#46;部门')<br />go</p><p>--删除测试<br />drop table tb</p>
页: [1]
查看完整版本: 逐月对比的交叉表处理