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

来源:互联网 发布:淘宝客服工作计划表 编辑:程序博客网 时间:2024/05/17 07:22


/*

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

*/


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

 

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/feixianxxx/archive/2010/01/25/5256026.aspx

原创粉丝点击