最近有一個需求:統計每日充值/消費以後的餘額,對於這種需求,其實也很簡單,只須要在每次充值/消費後,計算下餘額,而後保存下來就能夠了。可是對於這種需求,一條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;