如何在MySQL中为每天的每个小时分组数据

时间:2017-09-10 07:52:06

标签: mysql

我想创建一个图表,以查看一天中每个小时的某些表现。

这是表格:

id  |   clicks   |   timestamp  
------------------------------
1   |   1        |   2017-05-15 16:05:03  
2   |   1        |   2017-05-15 16:05:01  
3   |   2        |   2017-05-15 17:05:37 
4   |   1        |   2017-05-15 18:21:00  
5   |   1        |   2017-05-16 14:44:47  
6   |   3        |   2017-05-16 14:45:04  
7   |   1        |   2017-05-17 08:40:52  
8   |   1        |   2017-05-17 08:40:56  
9   |   2        |   2017-05-17 08:36:35

期望的输出:

id  |   clicks   |   timestamp  
------------------------------
1    |   0       |   01:00:00  
2    |   0       |   02:00:00  
3    |   0       |   03:00:00  
4    |   0       |   04:00:00  
5    |   0       |   05:00:00  
6    |   0       |   06:00:00  
7    |   0       |   07:00:00  
8    |   4       |   08:00:00  
9    |   0       |   09:00:00  
10   |   0       |   10:00:00  
11   |   0       |   11:00:00  
12   |   0       |   12:00:00  
13   |   0       |   13:00:00  
14   |   4       |   14:00:00  
15   |   0       |   15:00:00  
16   |   2       |   16:00:00  
17   |   2       |   17:00:00  
18   |   1       |   18:00:00  
19   |   0       |   19:00:00   
20   |   0       |   20:00:00
21   |   0       |   21:00:00 
22   |   0       |   22:00:00 
23   |   0       |   23:00:00 
00   |   0       |   00:00:00 

如果没有点击,我需要在点击次数上加0,并将当天分为24小时。例如,22:00:00的点击次数包括:22:00:00 - 22:59:59

如何对它们进行分组?我已经尝试过小时(时间戳)'但它并没有给我预期的结果。

1 个答案:

答案 0 :(得分:0)

你需要一个24小时的表来建立一个静态表或一个联合作为

select t.id, sum(ifnull(a.click,0),  hour(a.timestamp) from (

   select 1 as id,  O as my_order
   from dual
   union 
   select 2, 1
   from dual
   union 
   select 3, 2
   from dual
   union
   .....

   select 00, 24 
   from dual ) t
  left join my_table  a on t.id = a.id and a.date(timestamp) = your_date

  group by  t.id, hour(a.timestamp) 
  order by t.my_order