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


  最近項目碰到一個新的需求,統計每日充值/消費之后的余額。對於這種需求,其實也很簡單,只需要在每次充值/消費后,計算下余額,然后保存下來就可以了。但是對於這種需求,一條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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM