日期:2014-05-19  浏览次数:20477 次

求字段数据相加的语句或存储过程 全部分了  谢谢
ID                 name         sex           age                 qunty         qunty2
1 姓名1 1 15 455.0 500.0
2 姓名2 2 16 334.0 520.0
3 姓名3 1 17 34.0 451.0
4 姓名4 2 18 458.0 522.0
5 姓名5 1 19 435.0 504.0
6 姓名6 2 20 234.0 560.0
7 姓名7 1 21 345.0 855.0

想的到的结果是
  qunty2 = 本记录的qunty         +上一条记录的 qunty2
 qunty          可能为NULL
比如
  qunty         qunty2
455.0 500.0
334.0 520.0
34.0 451.0

结果是  

qunty         qunty2
455.0 455.0
334.0 789
34.0 823


请问高手怎么 解决
可以写 SQL语句 或存储过程 



------解决方案--------------------
select qunty,qunty2=(select sum(qunty)from ta where id!> a.id)
from ta as a
------解决方案--------------------
declare @t table(ID int,qunty real,qunty2 real)

insert @t
select 1,455,500 union all
select 2,334,520 union all
select 3,34,451

select qunty,qunty2=(select sum(qunty)from @t where id <=a.id)
from @t as a

/*
qunty qunty2
455.0 455.0
334.0 789.0
34.0 823.0
*/
------解决方案--------------------
declare @t table(ID int,qunty real,qunty2 real)

insert @t
select 1,455,500 union all
select 2,334,520 union all
select 3,34,451

select id,isnull(a.qunty,0) qunty,
qunty2=isnull(a.qunty,0)+isnull((select qunty2 from @t where id=a.id-1),0)
from @t as a

-------
1 455.0 455.0
2 334.0 834.0
3 34.0 554.0

------解决方案--------------------
--加一个判断就行了
select qunty,qunty2=(select sum(case when qunty is null then 0 else qunty end)from ta where id!> a.id)
from ta as a