1

我正在尝试构建一个查询以获取特定日期(或今天)每小时的数据计数。我得到的主要问题是我必须显示一天中所有 24 小时的计数,即使该特定时间不存在数据。那时它必须显示计数为零。到目前为止,我已经提出了以下查询。

SELECT   Hour
  ,      COUNT(created_on) AS `user_count`
FROM     users
  RIGHT JOIN (
                   SELECT  0 AS Hour
         UNION ALL SELECT  1 UNION ALL SELECT  2 UNION ALL SELECT  3
         UNION ALL SELECT  4 UNION ALL SELECT  5 UNION ALL SELECT  6
         UNION ALL SELECT  7 UNION ALL SELECT  8 UNION ALL SELECT  9
         UNION ALL SELECT 10 UNION ALL SELECT 11 UNION ALL SELECT 12
         UNION ALL SELECT 13 UNION ALL SELECT 14 UNION ALL SELECT 15
         UNION ALL SELECT 16 UNION ALL SELECT 17 UNION ALL SELECT 18
         UNION ALL SELECT 19 UNION ALL SELECT 20 UNION ALL SELECT 21
         UNION ALL SELECT 22 UNION ALL SELECT 23
  )      AS AllHours ON HOUR(created_on) = Hour
WHERE    created_on BETWEEN '2013-04-26' AND NOW() OR created_on IS NULL
GROUP BY Hour
ORDER BY Hour
4

1 回答 1

2

只需更改GROUP BY为:

GROUP BY HOUR(created_on)

您的查询应为:

SELECT   HOUR(created_on) AS Hour,
         COUNT(created_on) AS `user_count`
FROM     users
WHERE    created_on BETWEEN '2013-04-26' AND NOW() OR created_on IS NULL
GROUP BY HOUR(created_on)
ORDER BY Hour
于 2013-04-26T09:50:36.513 回答