mysql-count如果泛型值介于

lx0bsm1f  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(320)

这是我的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中可能吗?

lkaoscv7

lkaoscv71#

最棘手的部分是生成数字。剩下的只是 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;

相关问题