ORACLE SQL - 根据前一行数据求和

ORACLE SQL - sum based on previous row data

我有一个 table 看起来像这样:

tran_date tran_num tran_type tran_status amount
2/12/2021 74 SG N 1461
9/1/2021 357 SG4 N 2058
10/27/2021 46 SG4 Y -2058
10/27/2021 47 SG N 2058

如果按 tran_date 和 tran_num 排序,我想确定具有负数的行并将前一行的总和设为 0。

预期输出:

tran_date tran_num tran_type tran_status amount
2/12/2021 74 SG N 1461
10/27/2021 46 SG4 Y 0
10/27/2021 47 SG N 2058

您可以尝试在 sub-query 中使用滞后函数,然后像这样计算数量:

select x.tran_date,x.tran_num, x.tran_type, x.tran_status,
case 
    when x.amount<0 then x.amount + x.lag_win
    else x.amount
end amount
from 
(
select tt.*, 
       lag(amount,1) over (order by tran_date,tran_num) lag_win,
       abs(tt.amount)+lead (amount,1,1) over (order by tran_date,tran_num) pseudo_col
from tran_table tt
)x
where pseudo_col!=0

结果:

12.02.2021  74  SG  N   1461
27.10.2021  46  SG4 Y   0
27.10.2021  47  SG  N   2058