Calculate balance with mysql

后端 未结 3 739
野的像风
野的像风 2020-12-14 13:20

I have a table which contains the following data:

ID      In       Out 
1      100.00    0.00   
2       10.00    0.00   
3        0.00   70.00    
4                 


        
3条回答
  •  失恋的感觉
    2020-12-14 13:40

    A simple LEFT JOIN will suffice:

    SELECT t.ID, t.In, t.Out, (SUM(t2.In) - SUM(t2.Out)) Balance
    FROM mytable t
        LEFT JOIN mytable t2 ON b2.ID <= b.ID
    GROUP BY b.ID
    

    Or subquery (which as it turns out is about twice as fast)

    SELECT t.ID, t.In, t.Out,
        (SELECT SUM(t2.In) - SUM(t2.Out) FROM mytable t2 WHERE t2.ID <= t.ID) Balance
    FROM mytable t;
    

提交回复
热议问题