试图从SQL获取24小时的数据

时间:2015-09-01 12:24:59

标签: mysql sql database fetch

我对SQL不太熟练,所以希望有人可以帮助我。

我的表格中有一个date_of_post列,如下所示(示例)2015-08-31 11:00:00

我使用INTERVAL 1 DAY获取过去24小时。然而,它看起来比过去24小时还要多。这是我用来获取数据的查询

SELECT DATE_ADD(date(t.date_of_post),
       INTERVAL hour(t.date_of_post) HOUR) AS dateTime,
       count(*) as entries 
FROM `soc_stat` t 
WHERE `main_tag` = 'morgenmad' 
  AND t.date_of_post > DATE_SUB(CURDATE(), INTERVAL 1 DAY) 
GROUP BY date(t.date_of_post), hour(t.date_of_post)

它返回以下内容:

2015-08-31 11:00:00 = 11
2015-08-31 12:00:00 = 2
2015-08-31 13:00:00 = 3
2015-08-31 14:00:00 = 3
2015-08-31 15:00:00 = 1
2015-08-31 16:00:00 = 3
2015-08-31 17:00:00 = 2
2015-08-31 19:00:00 = 1
2015-09-01 04:00:00 = 1
2015-09-01 05:00:00 = 3
2015-09-01 06:00:00 = 9
2015-09-01 07:00:00 = 33
2015-09-01 08:00:00 = 38
2015-09-01 09:00:00 = 29
2015-09-01 10:00:00 = 13
2015-09-01 11:00:00 = 12
2015-09-01 12:00:00 = 6
2015-09-01 13:00:00 = 5

我不明白11:00:0012:00:00中存在13:00:002015-08-312015-09-01的原因。它不应该只返回过去24小时吗?

2 个答案:

答案 0 :(得分:1)

.table-header-rotated th.rotate-45 { height: 80px; width: 40px; min-width: 40px; max-width: 40px; position: relative; vertical-align: bottom; padding: 0; font-size: 12px; line-height: 0.8; white-space: nowrap; } 返回“今天的开头”。将其替换为CURDATE()

答案 1 :(得分:1)

视觉效果可能有所帮助。如果你使用别名坚持使用它们。当您使用聚合函数(如count)时,将按所有非聚合列进行分组。

for me it is 2015-09-01 08:47:00

create table soc_stat
(   id int auto_increment primary key,
    main_tag varchar(20) not null,
    date_of_post datetime not null
);
truncate table soc_stat;
insert soc_stat (main_tag,date_of_post) values  ('morgenmad','2015-09-02 11:00:00');
insert soc_stat (main_tag,date_of_post) values  ('morgenmad','2015-09-01 11:00:00');
insert soc_stat (main_tag,date_of_post) values  ('morgenmad','2015-09-01 09:00:00');
insert soc_stat (main_tag,date_of_post) values  ('morgenmad','2015-09-01 08:00:00');
insert soc_stat (main_tag,date_of_post) values  ('morgenmad','2015-09-01 07:00:00');
insert soc_stat (main_tag,date_of_post) values  ('morgenmad','2015-08-31 09:00:00');
insert soc_stat (main_tag,date_of_post) values  ('morgenmad','2015-08-31 08:00:00');
insert soc_stat (main_tag,date_of_post) values  ('morgenmad','2015-08-31 07:00:00');

SELECT date(t.date_of_post) dt, hour(t.date_of_post) hr,count(*) as entries 
FROM `soc_stat` t  
WHERE t.`main_tag` = 'morgenmad'  
AND t.date_of_post between DATE_SUB(now(), INTERVAL 1 DAY) and now() 
GROUP BY dt,hr 
order by t.date_of_post desc;

+------------+------+---------+
| dt         | hr   | entries |
+------------+------+---------+
| 2015-09-01 |    8 |       1 |
| 2015-09-01 |    7 |       1 |
| 2015-08-31 |    9 |       1 |
+------------+------+---------+