select t.*,
(case when b >= running_a then a
when b >= running_a - a then b - (running_a - a)
else 0
end) as new_a
from (select t.*, sum(a) over (order by ?) as running_a
from t
) t
SQL> with test (a, b) as
2 -- sample data
3 (select 0, 60 from dual union all
4 select 88, 0 from dual union all
5 select 32, 0 from dual union all
6 select 7, 0 from dual
7 ),
8 -- query you need begins here
9 temp as
10 (select a,
11 max(b) over (order by null) b
12 from test
13 )
14 select
15 x.a,
16 case when x.a = 0 then y.b
17 else case when x.a > y.b then y.b
18 else x.b
19 end
20 end b
21 from test x left join temp y on x.a = y.a
22 order by x.a;
A B
---------- ----------
0 60
7 0
32 0
88 60
SQL>
SQL> with test (a, b) as
2 -- sample data
3 (select 0, 75 from dual union all
4 select 21, 0 from dual union all
5 select 12, 0 from dual union all
6 select 42, 0 from dual
7 ),
8 -- query you need begins here
9 temp as
10 (select a,
11 max(b) over (order by null) b
12 from test
13 )
14 select
15 x.a,
16 case when x.a = 0 then y.b
17 else x.a
18 end b
19 from test x left join temp y on x.a = y.a
20 order by x.a;
A B
---------- ----------
0 75
12 12
21 21
42 42
SQL>
2条答案
按热度按时间yzckvree1#
sql表表示无序集。但是你的结果假设是有序的。我将假设有一个排序列,并将其表示为
?
.这是一个累加和问题——用算术:
这是一把小提琴。
ylamdve62#
我就是这样理解这个问题的。