[英]Subtract current row value by previous row value and get balance amount to current row
我需要通过从前一行的值中减去当前行值来获得balanceAmount
。 预期结果如下。
这是我当前的查询
select
pp.*,
pp.topupAmount - sum(pp.chargeAmount) over (over by pp.ROW_NUM rows unbounded preceding) AS balanceAmount
from
(select
row_number() over (order by ppc.sortDate) ROW_NUM, ppc.*
from
(select 0 as topupAmount, t1.chargeAmount, t1.sortDate
from t1
union all
select t2.topupAmount, 0 as chargeAmount, t2.sortDate
from t2) as ppc
) as pp
order by
pp.ROW_NUM
这是我从上面的查询中得到的
我怎么能做到这一点?
您可以使用窗口函数:
select
t.*,
sum(topupAmount - chargeAmount) over(order by row_num) balanceAmount
from mytable t
实际上,通过查看您的查询, row_num
似乎是一个生成的列,因此您可能想要:
select
t.*,
sum(topupAmount - chargeAmount) over(order by sortDate) balanceAmount
from mytable t
你需要窗口函数:
select t.*, sum(topupAmount - chargeAmount) over (order by sortDate) as balanceAmount
from table t;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.