sql 累加前面的值

sql 累加前面的值
id 金额 时间
1 120 1006(注:表示2010年6月)
2 130 1007
3 110 1008
4 100 1009
。。。。

求: 可用余额 可用余额 = 比它时间前的金额总数

第1个回答  推荐于2018-03-29
select *,余额=(select sum(金额) from table1 where 时间<=t1.时间) from table1 t1
select *,余额=(select sum(金额) from table1 where 时间<t1.时间) from table1 t1本回答被提问者和网友采纳
第2个回答  2010-12-30
如果你已经知道某ID的时间,那就好办了,如下 :
Select Sum(金额)
From table1
Where 时间 < ‘...' (你某个ID对应的时间)

如果你是想列出全部的ID的可用余额,就要用子查询了,性能会较差,如下:
Select id, 金额 , 时间 , 可用余额 = (select sum(金额) from table1 t1 where 时间 < t2.时间)
From table1 t2
第3个回答  2010-12-30
这个容易,用这个肯定可以

select id, 金额, 时间, (select sum(金额) from tab where 时间 < t1.时间)
from tab t1
第4个回答  2010-12-30
select *,(select sum(金额) from tb where id<t.id) as 可用余额 from tb t
这个回答应该可以,或者下面这个
select *,(select sum(金额) from tb where id<=t.id) as 可用余额 from tb t
第5个回答  2010-12-30
SELECT A.*
[可用余额]=(SELECT SUM(金额) FROM TB WHERE CONVERT(DATETIME, ‘20’+时间+‘01’)<= CONVERT(DATETIME,‘20’+A.时间+‘01’))
FROM TB A
相似回答