MySQL实现阶段累加的sql写法 ,eq:统计余额

时间:2023-03-09 17:07:24
MySQL实现阶段累加的sql写法 ,eq:统计余额

  最近项目碰到一个新的需求,统计每日充值/消费之后的余额。对于这种需求,其实也很简单,只需要在每次充值/消费后,计算下余额,然后保存下来就可以了。但是对于这种需求,一条sql就能搞定,都不需要做冗余字段。

  用图表展示会更详细:

          MySQL实现阶段累加的sql写法 ,eq:统计余额

  要求的结果:

        MySQL实现阶段累加的sql写法 ,eq:统计余额

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