获取从午夜到现在的差距的每小时数据

时间:2016-06-23 22:53:12

标签: mysql

我使用下面的代码来生成从午夜到现在的数据。

SELECT CONCAT(Hour, ':00-', Hour+1, ':00') AS Hours, IFNULL(COUNT(product_id), 0) AS `total_count`
FROM     clicks
  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(clicked_at) = Hour
WHERE   ( clicked_at BETWEEN CURRENT_DATE() AND NOW()  OR clicked_at IS NULL ) AND clicks.site='awesome-site.com'
GROUP BY Hour
ORDER BY Hour

我需要代码返回类似

的内容
Hours     total_count
----------------------
0:00-1:00     19
1:00-2:00     2
2:00-3:00     0
3:00-4:00     0
4:00-5:00     0
5:00-6:00     1
6:00-7:00     0
7:00-8:00     0
8:00-9:00     0
9:00-10:00    4
10:00-11:00   2
11:00-12:00   0
12:00-13:00   17
13:00-14:00   1

问题是上面的查询返回是返回带有时间列的间隙的数据;类似的东西:

 Hours     total_count
    ----------------------
    0:00-1:00     19
    1:00-2:00     2
    5:00-6:00     1
    9:00-10:00    4
    10:00-11:00   2
    12:00-13:00   17
    13:00-14:00   1

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

右连接是正确的方法,但您在where语句中使用clicks表中的列。而是将过滤器放在on

SELECT CONCAT(Hour, ':00-', Hour+1, ':00') AS Hours, IFNULL(COUNT(product_id), 0) AS `total_count`
FROM     clicks
  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(clicked_at) = Hour
  and   ( clicked_at BETWEEN CURRENT_DATE() AND NOW()  OR clicked_at IS NULL ) AND clicks.site='awesome-site.com'
GROUP BY Hour
ORDER BY Hour

答案 1 :(得分:1)

一个简单的潜在解决方案就是让一个单独的表格显示一天中的所有小时数(因为唯一的问题似乎是在一定时间内有0个条目):

Hours
-------------
0:00-1:00
1:00-2:00
2:00-3:00
...
22:00-23:00
23:00-24:00

然后JOIN对于您拥有的另一个表格,我认为基本上您所做的其他所有事情都应该与IFNULLWHERE ( clicked_at BETWEEN CURRENT_DATE() AND NOW() ...

一起使用