高效的累进总和

时间:2013-03-14 06:31:24

标签: sql performance oracle

我有下表:

+----+-------+
| id | value |
+----+-------+
|  1 |    10 |
|  2 |    11 |
|  3 |    12 |
+----+-------+

我想动态计算一列来汇总前面所有行的value,得出类似的结果:

+----+-------+--------+
| id | value | offset |
+----+-------+--------+
|  1 |    10 |      0 |
|  2 |    11 |     10 |
|  3 |    12 |     21 |
+----+-------+--------+

有效的方法是什么?

2 个答案:

答案 0 :(得分:2)

积分转为Egor Skriptunoff

select 
  id,
  value,
  nvl(
    sum(value) over (
      order by id rows between unbounded preceding and 1 preceding
    ), 0) as offset
from table

分析函数sum的优点在于它是渐进的,因为在每次迭代中,引擎都会记住为前一行计算的值,并且只将前一行的value添加到总数。换句话说,对于要计算的每个offset,它将前一行offsetvalue相加。这非常有效,可以很好地扩展。

答案 1 :(得分:0)

如果您的id值与1,2,3 etc..相似,那么

select a.*,(select sum(decode(a.id,1,0,b.value)) off_set from table b where b.id<=a.id-1)
from table a;

如果id's未按顺序排列,请尝试以下代码

select a.*,(select sum(decode(a.rn,1,0,b.value)) off_set from (select table.*,rownum rn from table) b 
           where b.rn<=a.rn-1)
from (select table.*,rownum rn from table) a;