SQL如何实现:同列数据逐行相加?

2024-11-26 08:43:35
推荐回答(2个)
回答1:

给一个DB2的
SELECT t2.A, SUM(t1.A)
FROM (SELECT a, ROW_NUMBER() OVER(ORDER BY A) RK from tab) t1, (SELECT a, ROW_NUMBER() OVER(ORDER BY A) RK from tab) t2
WHERE t1.rk <= t2.rk
group by t2.a
ORDER BY T2.A

-------------------------
....+....1....+....2....+....3....+....4....+....5
A SUM ( T1 . A )
11.25 11.25
25.25 36.50
50.00 86.50
60.00 146.50

ORACLE最好办
SELECT t2.A, SUM(t1.A)
FROM (SELECT a, rownum RK from tab) t1
(SELECT a, rownum RK from tab) t2
WHERE t1.rk <= t2.rk
group by t2.a
ORDER BY T2.A

关键是求得行号

如果你所有的数据都是唯一的,并且是递增排列了,那也有另外一个办法的
SELECT t2.a, sum(t1.a)
FROM TAB t1, tab t2
WHERE t1.a <= t2.a
group by t2.a

回答2:

declare @i1 float
declare @i2 float
set @i1=0
set @i2=0
update table1 set @i1=@i2,@i2=[A]+@i1,[B]=@i2