2015-08-25 28 views
0

我正試圖在SQL中完成此操作。邏輯是從第一個數字開始的遞歸添加。任何幫助與理解oracle sql執行數字字段的遞歸添加

數據具有

num_field 
22 
10 
20 
30 
1 
7 
7 

數據要

num_field Derived 
22   22 
10   32 
20   52 
30   82 
1   83 
7   90 
7   97 

下面是表創建腳本數據具有

CREATE TABLE HAVE (num_field 
number(4)); 
Insert into HAVE (num_field) 
Values (22); 
Insert into HAVE (num_field) 
Values (10); 
Insert into HAVE (num_field) 
Values (20); 
Insert into HAVE (num_field) 
Values (30); 
Insert into HAVE (num_field) 
Values (1); 
Insert into HAVE (num_field) 
Values (7); 
Insert into HAVE (num_field) 
Values (7); 

任何有興趣,下面的SQL聲明解決了我的問題 SELECT num_field ,SUM (num_field) OVER (ORDER BY rownum ROWS UNBOUNDED PRECEDING) derived from HAVE;

+0

在這種情況下,RANGE子句是多餘的,如果對SUM函數使用ORDER BY,則RANGE在分區中的第一行和正在評估的行之間非常相同, – Husqvik

+0

感謝@ Husqvik獲取信息。我在進一步深入研究RANGE(儘管它適用於我自己的實例,因爲rownum始終是唯一的)之後,我意識到它並不是正確的方法 – user2008558

回答

0
with x as (
select num_field, row_number() over(order by null) as rn 
,nvl(lag(num_field) over(order by null) , 0) as prev 
from tablename 
) 
select num_field, 
case when rn = (select max(rn) from x) then num_field + 
       (select prev from x where rn = (select max(rn)-1 from x)) 
else num_field + prev 
end as derived 
from x 

您可以使用lag獲取上一行的值,然後加起來。

+1

,或者,如果您要使用分析函數,則SUM() ! – Boneist

+0

感謝您的解決方案的vkp。它沒有讓我獲得我期待的結果 – user2008558