oracle sql执行递归添加的数字字段

时间:2015-08-25 16:30:37

标签: 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

以下是包含数据HAVE

的表创建脚本
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;

1 个答案:

答案 0 :(得分: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获取上一行的值,然后加起来。