简体   繁体   中英

Subtract current row value by previous row value and get balance amount to current row

I need to get the balanceAmount by subtracting the current row value from the previous row's value. Expected result is as below.

预期结果

Here is my current query

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

This is what I am getting from above query

当前结果

How could I achieve this?

You can use window functions:

select
    t.*,
    sum(topupAmount - chargeAmount) over(order by row_num) balanceAmount
from mytable t

Actually by looking at your query it seems like row_num is a generated column, so you likely want:

select
    t.*,
    sum(topupAmount - chargeAmount) over(order by sortDate) balanceAmount
from mytable t

You need window function :

select t.*, sum(topupAmount - chargeAmount) over (order by sortDate) as balanceAmount
from table t;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM