1. 程式人生 > >MySQL實現階段累加的sql寫法 ,eq:統計余額

MySQL實現階段累加的sql寫法 ,eq:統計余額

要求 where sele ima http mage fault 階段 文章

  最近項目碰到一個新的需求,統計每日充值/消費之後的余額。對於這種需求,其實也很簡單,只需要在每次充值/消費後,計算下余額,然後保存下來就可以了。但是對於這種需求,一條sql就能搞定,都不需要做冗余字段。

  用圖表展示會更詳細:

          技術分享圖片

  要求的結果:

        技術分享圖片

MySQL寫法一:

select t.*
,(select sum(price) from t_charge temp where temp.date <= t.date) as total_price
from t_charge t
group by t.id;

寫法二:

select t.*, sum
(temp.price) as total_price from t_charge t,t_charge temp where t.date <= temp.date group by t.id;

  引用文章地址:https://segmentfault.com/a/1190000017894402

MySQL實現階段累加的sql寫法 ,eq:統計余額