本篇文章給大家帶來的內容是關于mysql實現階段累加的sql寫法(代碼示例),有一定的參考價值,有需要的朋友可以參考一下,希望對你有所幫助。
最近有一個需求:統計每日充值/消費之后的余額,對于這種需求,其實也很簡單,只需要在每次充值/消費后,計算下余額,然后保存下來就可以了。但是對于這種需求,一條sql就能搞定,都不需要做冗余字段
圖表展示這個場景可能更直白
需要的結果
寫法一:
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;
? 版權聲明
文章版權歸作者所有,未經允許請勿轉載。
THE END