[已解决问题] SQL Server 的数据累加问题?
提问时间: 2008-10-07 08:49
悬赏分:30 浏览:264 次

有表: id  value

    1  10

    2  20  

    3  50

    4  100

请问如何直接通过SQL语句得到查询结果:

  id  value

  1    10  

  2    30  // 30 = 20 + 10

  3    80  // 80 = 50 + 30

  4    180  // 180 = 100 + 80

如果使用游标如何实现这个功能?如果不使用游标又如何实现这个功能?要实现这个功能有有可能吗?

提问者:沈啣结 - 初学一级
最佳答案

 


Code
declare @t table(id int ,num int)
insert @t
select 1,10 union all
select 2,20 union all
select 3,50 union all
select 4,100
select
a.id,(
select sum(num) from @t b where b.id<=a.id)
from @t a

 

 

 

 

2008/10/7 13:52:49 回答者:Robot·H


提问者对于答案的评价:谢谢。
其它回答(1)

Robot-H

请问怎么直接将结果更新至 @t 中呢? 有不用游标的方法吗?要用中间表吗?


1个月前   回答者: - 菜鸟二级
评论
1个月前   Robot·H :
@蝎
关于这个可以看看table variable,temprory table,cursor 等。

请问怎么直接将结果更新至 @t 中呢? 有不用游标的方法吗?要用中间表吗?
您的意思是?
insert into @t
select ..............where ..............

或者
select * into #t from ..
1个月前   :
Update @t
set ...
From @t
where ....
这样可以吗?
insert into @t
select ..............where ..............
只会插入新的数据,我想更新原表值
   您需要登录以后才能回答!
 

我要提问

我的问题


快到期问题



> 问题排行榜

相关内容

相关链接