[英]How to Group data for every hour of the day in MySQL
I'd like to create a chart to see some performance for every hours of a day. 我想创建一个图表,以查看一天中每个小时的性能。
Here's the table: 这是桌子:
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
Desired output: 所需的输出:
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
What I need is to put a number 0 to the clicks if there are no clicks and to split the day to 24 hours. 我需要的是,如果没有点击次数,则将点击次数设为0,然后将一天划分为24小时。 For example, 22:00:00
's clicks would include: 22:00:00 - 22:59:59
. 例如, 22:00:00
的点击将包括: 22:00:00 - 22:59:59
。
How's it possible to group them? 如何将它们分组? I've tried to 'GROUP BY HOUR (timestamp)' but it wasn't giving me the desired result. 我尝试过“按小时分组(时间戳记)”,但未达到预期效果。
You need a table for the 24 for hours youn can buil a static table or a union as 您需要一个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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.