[英]SQL Query to get results on a 24 hour graph
I have the following structure to store clicks from a website on a Mysql database: 我具有以下结构,可将来自网站的点击存储在Mysql数据库中:
select * from contenido_clicks;
+-------------+-------------+------------+
| idContenido | fecha_click | servicetag |
+-------------+-------------+------------+
| 5 | 1392829606 | HJCS302 |
| 8 | 1392832379 | HJCS302 |
| 5 | 1392832433 | HJCS302 |
| 5 | 1392832435 | HJCS302 |
| 5 | 1392832437 | HJCS302 |
And so on...
Here I have lots on entries from different days and hours, and I need to get all of them and place on a 24 hours graph, to show the hours in the day that people makes more clicks. 在这里,我有很多来自不同日期和时间的条目,我需要将它们全部收集并放在24小时图表上,以显示人们点击次数在一天中的小时数。 I can get the clicks per hour with: 我可以通过以下方式获得每小时的点击次数:
SELECT cc.fecha_click div 3600 as Horas, COUNT(cc.idContenido) as Clicks
FROM contenido_clicks cc
GROUP BY fecha_click div 3600 ASC
But I dont know how to merge them in a 24 hour table. 但是我不知道如何将它们合并到24小时的表格中。
Any ideas? 有任何想法吗?
Create a Horas domain table with 24 rows and left join your contenido_clicks table with it 创建一个包含24行的Horas域表,然后将其与contenido_clicks表一起加入
create table Horas
(
Hora integer not null
)
Insert into Horas (Hora) vlaues (0)
Insert into Horas (Hora) vlaues (1)
.
.
.
Insert into Horas (Hora) vlaues (23)
select *
from Horas h
left join (
SELECT cc.fecha_click div 3600 as Horas, COUNT(cc.idContenido) as Clicks
FROM contenido_clicks cc
GROUP BY fecha_click div 3600
) as hh on hh.Hora = h.Hora
order by h.Hora
I think you want to do some thing like this 我想你想做这样的事情
SELECT *
FROM contenido_clicks
WHERE DATE_ADD(NOW(), INTERVAL 24 HOUR) > fecha_click
I think this will solve your problem 我认为这可以解决您的问题
Thanks to the solution provided by jean, I write the following query: 感谢Jean提供的解决方案,我编写了以下查询:
SELECT h.hora, COUNT(cc.idContenido) as Clicks
FROM horas h
LEFT JOIN contenido_clicks cc ON h.hora = DATE_FORMAT(FROM_UNIXTIME(cc.fecha_click), '%H')
GROUP BY h.hora;
And get the following result: 并得到以下结果:
+------+--------+
| hora | Clicks |
+------+--------+
| 0 | 0 |
| 1 | 0 |
| 2 | 0 |
| 3 | 0 |
| 4 | 0 |
| 5 | 0 |
| 6 | 0 |
| 7 | 0 |
| 8 | 0 |
| 9 | 5 |
| 10 | 3 |
| 11 | 7 |
| 12 | 4 |
| 13 | 3 |
| 14 | 0 |
| 15 | 5 |
| 16 | 1 |
| 17 | 5 |
| 18 | 8 |
| 19 | 0 |
| 20 | 0 |
| 21 | 1 |
| 22 | 0 |
| 23 | 0 |
+------+--------+
24 rows in set (0.00 sec)
Which are the correct results. 哪个是正确的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.