php - 我想使用日期和余额列总和而不是日期之间获取余额列数据的总和,按mysql中的customer_id分组
问题描述
这是我的mysql表,
customer_id balance date
1 300 1-1-2018
2 200 3-1-2018
1 100 5-1-2018
2 50 5-1-2018
1 30 6-1-2018
1 10 7-1-2018
4 50 7-1-2018
如果我从日期 1 到 5 选择,我想要这个结果
customer_id current previous total
1 400 40 440
2 250 0 250
3 0 50 50
解决方案
一种方法是使用一对计算聚合值的子查询。因此,您可以使用子查询选择指定日期范围内的总和以及该范围外的总和。然后添加coalesce
以替换null
为有效数量 (0)。
select
customer_id,
coalesce(current, 0),
coalesce(previous, 0),
coalesce(current, 0) + coalesce(previous, 0) total
from
(
select
customer_id,
(
select sum(balance)
from balance b
where b.customer_id = a.customer_id
and b.date between '2018-01-01' and '2018-05-01'
group by b.customer_id
) current,
(
select sum(balance)
from balance c
where c.customer_id = a.customer_id
and c.date not between '2018-01-01' and '2018-05-01'
group by c.customer_id
) previous
from balance a
) c
推荐阅读
- sql - 在组标题中显示来自子查询的附件时出错
- reactjs - 为什么 Firebase 部署完整的反应应用程序而不是部署构建目录文件?
- javascript - InDesign 启动脚本
- python - 如何在 Win 上下载 Linux python 版本模块?
- elasticsearch - ElasticSearch 查询优化
- cmake - 简单的 CMAKE 教程有问题
- azure - 在模板参数中使用任务输出变量
- java - org.springframework.beans.factory.UnsatisfiedDependencyException:创建名为“brightspotService”的bean时出错
- ios - AVPlayerViewController 问题和疑问
- firebase - 我可以检索但不能有用地使用来自 firebase 数据库的数据