【问题标题】:MySQL: Select all dates between date range and get table data matching datesMySQL:选择日期范围内的所有日期并获取匹配日期的表数据
【发布时间】:2016-07-20 04:53:00
【问题描述】:

有一个表格,里面有这样的数据:

-----------------------
|   id   |    date    |
-----------------------
|   1    | 2016-07-11 |
|   2    | 2016-07-11 |
|   3    | 2016-07-15 |
|   4    | 2016-07-15 |
|   5    | 2016-07-15 |
|   6    | 2016-07-16 |
|   7    | 2016-07-19 |
|   8    | 2016-07-20 |
-----------------------

我想获取日期范围(所有日期)和每个日期的 ID 计数,当不存在记录时返回 0。

如果在 2016 年 7 月 10 日到 2016 年 7 月 20 日之间运行,结果应如下所示:

--------------------------
|    date    | count(id) |
--------------------------
| 2016-07-10 |     0     |
| 2016-07-11 |     2     |
| 2016-07-12 |     0     |
| 2016-07-13 |     0     |
| 2016-07-14 |     0     |
| 2016-07-15 |     3     |
| 2016-07-16 |     1     |
| 2016-07-17 |     0     |
| 2016-07-18 |     0     |
| 2016-07-19 |     1     |
| 2016-07-20 |     1     |
--------------------------

我找到了getting a date range 的解决方案,但不知道如何让它计算表格中这些日期存在的 ID。

谢谢!

【问题讨论】:

  • 您可以使用聚合函数“计数”,通过您的选择查询来计算特定日期的记录数。
  • 创建永久的每日或每月Helper Tables 一次并经常使用它们。可以更快地加入,每次都将它们快速组合在一起。
  • 德鲁,你确定吗?

标签: mysql date


【解决方案1】:

我通过修改获取所有日期的解决方案中给出的查询来解决这个问题。

以下查询返回所有日期,如果存在任何记录,则返回 ID 的计数:

select d.date, count(v.id) from 
(select adddate('1970-01-01',t4.i*10000 + t3.i*1000 + t2.i*100 + t1.i*10 + t0.i) date from
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t0,
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t1,
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2,
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3,
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t4) d
left join visitors v on d.date = v.date
where d.date between '2016-06-01' and '2016-06-30'
group by d.date
order by d.date

感谢您获取日期范围到@mark-bannister 和一个简单的连接查询匹配结果,排序得到解决方案。

【讨论】:

    【解决方案2】:

    请尝试以下方法,基本上需要一个 group by 来帮助您获得所需的结果。根据需要还具有带范围的 where 条件

    SELECT date ,count(date) from datetable group by date;
    

    【讨论】:

    • 即使没有记录,您也错过了获取范围内所有日期的部分。
    • 我确实提到您可以根据需要编写 where 条件,认为这不是您苦苦挣扎的部分:)
    【解决方案3】:

    简单地说,

    WHERE `date` BETWEEN '2016-07-10' AND '2016-07-20'
    

    【讨论】:

    • 我也想要数据中不存在的日期
    • 添加 NULL 检查:WHERE (d.date BETWEEN '2016-07-10' AND '2016-07-20' OR d.date IS NULL)
    • 就其本身而言,无济于事
    • 您的查询不完整,不能解决 OP 的问题,因为它不计算行数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-02
    • 2013-03-02
    • 2020-04-01
    • 1970-01-01
    • 2021-08-01
    相关资源
    最近更新 更多