Calculate delta(difference of current and previous row) in sql

前端 未结 3 1304
离开以前
离开以前 2020-12-05 16:29

I have a table like : trans is the name of the table for example

Id | Trans_Date          | Account_Id | Amount | Delta
------------------------------------         


        
相关标签:
3条回答
  • 2020-12-05 16:42

    Here's your original query modified accordingly:

    select
      tt1.id,
      tt1.amount,
      tt1.AccountId,
      (tt1.amount-ifnull(tt2.amount, 0)) as delta
    from trans tt1
      left outer JOIN trans tt2 on tt1.accountid = tt2.accountid
        and month(tt1.date1)-month(tt2.date1)=1;
    

    The month comparison is moved from where to on, which makes a difference for left join, and tt2.amount is replaced with ifnull(tt2.amount, 0).


    The UPDATE version of the script:

    update tt1
    set delta = (tt1.amount-ifnull(tt2.amount, 0))
    from trans tt1
      left outer JOIN trans tt2 on tt1.accountid = tt2.accountid
        and month(tt1.date1)-month(tt2.date1)=1;
    


    The correct MySQL syntax for the above update should actually be:

    update trans tt1 
                 left outer JOIN trans tt2 
                 on tt1.accountid = tt2.accountid 
                 and month(tt1.date1)-month(tt2.date1)=1 
    set tt1.delta = (tt1.amount-ifnull(tt2.amount, 0));
    

    (Thanks @pinkb.)

    0 讨论(0)
  • 2020-12-05 16:44

    You can use an inner query, but it's not necessarily the most efficient query.

    UPDATE trans
    SET Delta = Amount - 
    (SELECT Amount FROM trans t1
    WHERE t1.Trans_Date < trans.Trans_Date
    ORDER BY t1.Trans_Date DESC LIMIT 1)
    
    0 讨论(0)
  • 2020-12-05 17:01

    Can you "union all" your query with a query that simply selects the first item for each account with the initial balance set as the delta, and the ID of that record as the id for the delta record? The result would be ordered by ID. Dirty but is it applicable?

    0 讨论(0)
提交回复
热议问题