MySQL實現階段累加的sql寫法

  最近有一個需求:統計每日充值/消費以後的餘額,對於這種需求,其實也很簡單,只須要在每次充值/消費後,計算下餘額,而後保存下來就能夠了。可是對於這種需求,一條sql就能搞定,都不須要作冗餘字段sql

圖表展現這個場景可能更直白
segmentfault

須要的結果
學習

寫法一:區塊鏈

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;

寫法二:spa

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


歡迎訂閱「K叔區塊鏈」 - 專一於區塊鏈技術學習

博客地址: http://www.jouypub.com
簡書主頁: https://www.jianshu.com/u/756c9c8ae984
segmentfault主頁: https://segmentfault.com/blog/jouypub
騰訊雲主頁: https://cloud.tencent.com/developer/column/72548
相關文章
相關標籤/搜索