想要计算与Oracle SQL查询中先前金额的差额

时间:2020-06-11 10:30:49

标签: sql oracle

要计算与先前金额的差额。

Order   EVENT NO    DATE    AMOUNT  EVENT AMOUNT(Difference of previous amount)
1   1         11/6/2020     100     100
1   2   11/6/2020           200     100
1   3   11/6/2020           500     300

2 个答案:

答案 0 :(得分:0)

使用lag()

select t.*,
       (amount - lag(amount, 1, 0) over (partition by order order by event_no)) as diff
from t;

答案 1 :(得分:0)

您可以使用lag()函数,

select order,  event_no, date, amount, 
case when 
(amount-LAG(amount) OVER (ORDER BY date, event_no)) is null then amount
else (amount-LAG(amount) OVER (ORDER BY date, event_no))
end as event_amount
from table;