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

/*

*关于本条记录某一字段由上条记录的部分内容与本记录部分内容计算而来

*/

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(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*/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值