近来有一个需求:统计逐日充值/消耗以后的余额,关于这类需求,实在也很简单,只须要在每次充值/消耗后,盘算下余额,然后保留下来就可以够了。然则关于这类需求,一条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;
以上就是MySQL完成阶段累加的sql写法(代码示例)的细致内容,更多请关注ki4网别的相干文章!