日期:2014-05-18 浏览次数:20576 次
--> 测试数据:[T1]
if object_id('[T1]') is not null drop table [T1]
create table [T1](
[xh] varchar(4),
[gs] int,
[sl] int,
[ff1] varchar(2),
[ff1je] int,
[ff2] varchar(2),
[ff2je] int,
[id] int,
[年度] int,
[月份] int
)
insert [T1]
select '张1',100,300,'AA',1000,'BB',500,1,2012,1 union all
select '张2',200,400,'AA',1000,'BB',500,2,2012,1 union all
select '张3',200,500,null,0,null,0,3,2012,1 union all
select '张4',200,600,'AA',1000,null,0,4,2012,1 union all
select '张5',200,700,'AA',1000,null,0,5,2012,1 union all
select '张6',200,800,'AA',1000,null,0,6,2012,1 union all
select '张7',200,900,'AA',1000,'BB',100,7,2012,1 union all
select '张8',200,1000,'AA',1000,null,0,8,2012,1 union all
select '张9',200,1100,'AA',1000,null,0,9,2012,1 union all
select '张10',200,1200,'AA',1000,null,0,10,2012,1 union all
select '张11',200,1300,null,0,null,100,11,2012,1 union all
select '张1',200,1400,null,0,'CC',100,12,2012,2 union all
select '张2',200,1500,null,0,'CC',0,13,2012,2 union all
select '张3',200,1600,null,0,null,0,14,2012,2 union all
select '张4',200,1700,null,0,'DD',0,15,2012,2 union all
select '张5',200,1800,null,0,'DD',0,16,2012,2
select * from [T1]
--问题1:
select LTRIM(年度)+right('00'+LTRIM(月份),2)+right('00'+LTRIM(ID),2) as 编号
,年度,月份,ff from(
select ROW_NUMBER()over(partition by 月份 order by ff) as ID,* from(
select 年度,月份,ff1 as ff from [T1] union
select 年度,月份,ff2 as ff from [T1]
)a where ff is not null)b
--问题2:
with t
as(
select [xh],ltrim([月份])+'月份' as 月份,sum([sl]+[gs]) as total
from [T1] where RIGHT(xh,LEN(XH)-1) in('1','2','3','4') group by [xh],[月份]
)
select *
from t
pivot (sum([total]) for [月份] in([1月份],[2月份],[3月份],[4月份],[5月份],
[6月份],[7月份],[8月份],[9月份]))b
/*
xh 1月份 2月份 3月份 4月份 5月份 6月份 7月份 8月份 9月份
张1 400 1600 NULL NULL NULL NULL NULL NULL NULL
张2 600 1700 NULL NULL NULL NULL NULL NULL NULL
张3 700 1800 NULL NULL NULL NULL NULL NULL NULL
张4 800 1900 NULL NULL NULL NULL NULL NULL NULL
*/
我的异常网推荐解决方案:软件开发者薪资,http://www.aiyiweb.com/other/1391128.html