By using db<>fiddle, you agree to license everything you submit by Creative Commons CC0.
create table tableX (rownum int not null,
ACC_NET_AMOUNT int not null,
FC_NET_AMOUNT int not null);
insert into tableX (rownum, ACC_NET_AMOUNT, FC_NET_AMOUNT)
values (1, 40, 50)
, (2, 164, 2050)
, (3, 1513, 0)
, (4, 1000, 500)
, (5, 100, 0);
5 rows affected
with cte as
(
select ACC_NET_AMOUNT, fc_NET_AMOUNT
-- cumulative sums up to the previous rows
, coalesce(sum(ACC_NET_AMOUNT) over (order by rownum rows between unbounded preceding and 1 preceding) ,0) as cumacc
, coalesce(sum( FC_NET_AMOUNT) over (order by rownum rows between unbounded preceding and 1 preceding), 0) as cumfc
from tableX
)
select ACC_NET_AMOUNT, fc_NET_AMOUNT
, ca.CumResult - case when cumfc > cumacc then cumfc else cumacc end as Result
, ca.CumResult
from cte
cross apply
( select
case when cumfc+FC_NET_AMOUNT > cumacc + ACC_NET_AMOUNT
then cumfc+FC_NET_AMOUNT
else cumacc+ACC_NET_AMOUNT
end as CumResult) as ca
ACC_NET_AMOUNT | fc_NET_AMOUNT | Result | CumResult |
---|---|---|---|
40 | 50 | 50 | 50 |
164 | 2050 | 2050 | 2100 |
1513 | 0 | 0 | 2100 |
1000 | 500 | 617 | 2717 |
100 | 0 | 100 | 2817 |