2013-03-14 13 views
0

我有如下表:高效的進步和

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

我要實時計算的列來總結以前所有的行value,拿出這樣的:

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

什麼是有效的方法來做到這一點?

回答

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相加。這非常有效,並且很好地擴展。

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; 
+0

這是一種方法,但它不能按比例增長很好,試着在100,000行上運行它。 – abstractpaper 2013-03-14 06:59:27

+0

可能會使n行的差異 ,但我只是給出另一種獲得解決方案的方式! – Aspirant 2013-03-14 09:04:09