如何在mysql中按小时分组数据

时间:2013-04-26 09:43:50

标签: mysql

我正在尝试构建一个查询,以获取特定日期(或今天)每小时的数据计数。我得到的主要问题是我必须在一天中显示所有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

1 个答案:

答案 0 :(得分: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