Mysql结果每小时数据

时间:2013-02-12 18:05:59

标签: mysql date time

我正在尝试计算每小时分组的条目。 我在不同的网站上找到了一些有用的信息,请点击此处:MySQL Group By Hours

但结果并不是我所期待的。 我得到以下代码:

SELECT   CONCAT(Hour, ':00-', Hour+1, ':00') AS Hours,
     COUNT(`usage_time`) AS `usage` FROM `usage`
  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(`usage_time`) = Hour

WHERE `usage_function` LIKE 'PlayedWholeSong' AND `usage_date` = DATE_SUB(CURDATE(), INTERVAL 0 DAY) OR `usage_time` IS NULL
GROUP BY Hour
ORDER BY Hour

结果:

Hours       usage
2:00-3:00   0
4:00-5:00   6
6:00-7:00   2
8:00-9:00   3
9:00-10:00  20
10:00-11:00 1
14:00-15:00 14
15:00-16:00 1
16:00-17:00 32
17:00-18:00 10

由于这些是从今天开始的,因此我在19:00之后没有任何参赛作品。 此外,我没有看到00:00 - 01:00,03:00 - 04:00的参赛作品,还有其他几个缺席。 但我确实希望每24小时显示一个列表和结果,即使没有任何内容。 字符串的结果是在02:00 - 03:00之间显示0。 我今天学到了很多关于mysql的知识,但没有解决我的问题。

我希望你能学到一些东西,不必是代码,方向会很棒。

1 个答案:

答案 0 :(得分:1)

我个人更喜欢LEFT JOIN而不是RIGHT JOIN。这样,您就可以在WHERE中添加JOIN条件,但这不会限制您的搜索结果。试试这个:

SELECT   CONCAT(Hour, ':00-', Hour+1, ':00') AS Hours,
     COUNT(`usage_time`) AS `usage` 
FROM 
   (
         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 
      LEFT JOIN `usage` ON HOUR(`usage_time`) = Hour 
           AND `usage_function` LIKE 'PlayedWholeSong' 
           AND `usage_date` = DATE_SUB(CURDATE(), INTERVAL 0 DAY) 
GROUP BY Hour
ORDER BY Hour

这是一个简化的SQL Fiddle

祝你好运。