【问题标题】:Fill zero dates in GROUP BY MySQL在 GROUP BY MySQL 中填充零日期
【发布时间】:2022-08-18 16:19:51
【问题描述】:

我有这个查询:

SELECT date AS datekey, count(*) AS total
FROM `tags` AS `t`
         INNER JOIN `thing_tags` AS `tt` ON `tt`.`tag_id` = `t`.`tag_id`
         INNER JOIN `things` AS `t` ON `tt`.`thing_id` = `t`.`thing_id`
 WHERE `t`.`other_id` = 14
  AND date(`date`) >= \'2019-12-20\'

GROUP BY datekey
ORDER BY datekey DESC

这给了我这些结果:

2022-07-15,8
2022-07-12,16
2022-07-06,10
2022-07-01,3

我需要的是每一天的记录,即使计数为零:

(record for every day since 2019-12-20)
2022-07-06,10
2022-07-05,0
2022-07-04,0
2022-07-03,0
2022-07-02,0
2022-07-01,3

我希望我可以使用某种日期函数来创建一个结构,然后我可以加入该结构,但我不知道该怎么做。

    标签: mysql sql


    【解决方案1】:

    您可以在此处使用日历表,它只是一个包含您希望出现在输出中的所有日期的表。将此日历表左连接到tags 表,以确保您想要显示的所有日期都在结果集中。

    SELECT c.date datekey, COUNT(t.thing_id) AS total
    FROM calendar c
    LEFT JOIN tags t ON t.date = c.date
    INNER JOIN thing_tags tt ON tt.tag_id = t.tag_id
    INNER JOIN things t ON tt.thing_id = t.thing_id
    WHERE t.other_id = 14 AND c.date >= '2019-12-20'
    GROUP BY datekey
    ORDER BY datekey DESC;
    

    上面使用的calendar 表应包含从 2019-12-20 开始并持续到您想要的任何结束日期的日期。 See this SO question and answers 获取有关如何填充日历表的一些想法。

    【讨论】:

      猜你喜欢
      • 2011-01-29
      • 2018-07-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-03
      • 1970-01-01
      相关资源
      最近更新 更多