您的位置:首页 > 其它

【小小问题集合3---本条记录某一字段由上条记录的部分内容与本记录部分内容计算而来】

2010-01-25 23:07 405 查看
/*
*关于本条记录某一字段由上条记录的部分内容与本记录部分内容计算而来
*/

if OBJECT_ID('tb') is not null
drop table tb
go
create table tb (field1 int, field2 decimal(3,1) ,field3 decimal(3,1))
insert tb select
1, 2.3, 4.5 union select
2, 2.3, 3.4 union select
4, 3.4, 4.5 union select
6, 4.5, 5.6 union select
7, 5.6, 6.7
go
/*
想显示为:
field1 field2 field3 field4
1 2.3 4.5 0
2 2.3 3.4 -1.1
4 3.4 4.5 -2.2
6 4.5 5.6 -3.3
7 5.6 6.7 -4.4

field4的计算规则是,第一条为,
后面的就等于上一条的field4+本条的field2-本条的field3
*/
--2000
select *,
field4=case when field1=(select MIN(field1) from tb) then 0
else field2-field3+(select isnull(SUM(field2-field3),0) from tb where K.field1>field1 and field1<>(select MIN(field1) from tb)) end
from tb K
go
--2005
with cte as
(
select rn=row_number()over(order by field1),* from tb
)
, cte2 as
(
select *,field4=cast(0 as decimal(9,1)) from cte where rn=1
union all
select b.*,cast(a.field4+(b.field2-b.field3) as decimal(9,1)) from cte2 a join cte b on a.rn=b.rn-1
)
select * from cte2
/*
field1 field2 field3 field4
----------- --------------------------------------- --------------------------------------- ---------------------------------------
1 2.3 4.5 0.0
2 2.3 3.4 -1.1
4 3.4 4.5 -2.2
6 4.5 5.6 -3.3
7 5.6 6.7 -4.4*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: