mysql - MySQL - 如果通用值介于
问题描述
这是我的 MySQL 表:
+----+---------------------+---------------------+
| id | startDate | endDate |
+----+---------------------+---------------------+
| 1 | 2018-03-20 10:10:10 | 2018-10-02 21:44:00 |
+----+---------------------+---------------------+
| 2 | 2017-08-02 21:44:00 | 2017-08-03 11:00:00 |
+----+---------------------+---------------------+
| 3 | 2018-10-25 12:12:12 | 2018-11-25 12:22:33 |
+----+---------------------+---------------------+
| 4 | 2015-01-01 23:43:27 | 2018-12-29 22:12:35 |
+----+---------------------+---------------------
我喜欢做的是从本月开始的最后 12 个月,并检查每个月的第一天,这一天在startDate
和之间有多少行endDate
预期结果(2018 年 7 月 18 日):
+---------------------+-------+
| date | count |
+---------------------+-------+
| 2017-08-01 00:00:00 | 1 | (id 4)
+---------------------+-------+
| 2017-09-01 00:00:00 | 1 | (id 4)
+---------------------+-------+
| 2017-10-01 00:00:00 | 1 | (id 4)
+---------------------+-------+
| 2017-11-01 00:00:00 | 1 | (id 4)
+---------------------+-------+
| 2017-12-01 00:00:00 | 1 | (id 4)
+---------------------+-------+
| 2018-01-01 00:00:00 | 1 | (id 4)
+---------------------+-------+
| 2018-02-01 00:00:00 | 1 | (id 4)
+---------------------+-------+
| 2018-03-01 00:00:00 | 1 | (id 4)
+---------------------+-------+
| 2018-04-01 00:00:00 | 2 | (id 1 and 4)
+---------------------+-------+
| 2018-05-01 00:00:00 | 2 | (id 1 and 4)
+---------------------+-------+
| 2018-06-01 00:00:00 | 2 | (id 1 and 4)
+---------------------+-------+
| 2018-07-01 00:00:00 | 2 | (id 1 and 4)
+---------------------+-------+
在MySQL中可以吗?
解决方案
最棘手的部分是生成数字。剩下的就是JOIN
和GROUP BY
:
select d.dte, count(t.startdate)
from (select date('2017-08-01') as dte union all
select date('2017-09-01') as dte union all
. . .
select date('2018-07-01') as dte
) d left join
mysql_table t
on d.dte >= t.startdate and d.dte <= t.enddate
group by d.dte
order by d.dte;
推荐阅读
- cumulocity - 如何创建非全局但链接到库存的报告?
- python - 如何通过 python 请求库将 Starlette FormData 数据结构发送到 FastAPI 端点
- angular - 当我期待订阅时,双重响应
- php - 优化超过 10 万条记录的 MySQL 查询
- android - 如何在 Android Jetpack Compose 中传递可选的布尔参数?
- nestjs - Typeorm 按字符串插入外键
- android - 为什么 API 29 中缺少 ViewPropertyAnimatorRT?
- r - 网络分析 - 从现有网络生成随机空网络
- c# - 进程在 process.Start() 后立即退出,仅带参数
- java - Spring boot 计划的 cron 作业在部署多个实例时运行 2 次