MySQL实现阶段累加的sql写法

4次阅读

共计 523 个字符,预计需要花费 2 分钟才能阅读完成。

  最近有一个需求:统计每日充值 / 消费之后的余额,对于这种需求,其实也很简单,只需要在每次充值 / 消费后,计算下余额,然后保存下来就可以了。但是对于这种需求,一条 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;

欢迎订阅「K 叔区块链」– 专注于区块链技术学习 博客地址:http://www.jouypub.com 简书主页:https://www.jianshu.com/u/756c9c8ae984segmentfault 主页:https://segmentfault.com/blog/jouypub 腾讯云主页:https://cloud.tencent.com/developer/column/72548

正文完
 0

MySQL实现阶段累加的sql写法

4次阅读

共计 523 个字符,预计需要花费 2 分钟才能阅读完成。

  最近有一个需求:统计每日充值 / 消费之后的余额,对于这种需求,其实也很简单,只需要在每次充值 / 消费后,计算下余额,然后保存下来就可以了。但是对于这种需求,一条 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;

欢迎订阅「K 叔区块链」– 专注于区块链技术学习 博客地址:http://www.jouypub.com 简书主页:https://www.jianshu.com/u/756c9c8ae984segmentfault 主页:https://segmentfault.com/blog/jouypub 腾讯云主页:https://cloud.tencent.com/developer/column/72548

正文完
 0