简体   繁体   中英

Get records of last hour, last 2 hours…last n hours

I need to get the records of the last 24 hours but not group by hour like this:

SELECT HOUR(CompDate) AS hour, COUNT(1) AS action
FROM mytable
WHERE ((CompDate >= DATE_SUB(NOW(), INTERVAL 24 HOUR))
GROUP BY `hour`;

The above query will tell me that: hour 22 --> 6 actions, hour 21 --> 9 actions.

What I want to have is: 1 hour ago --> 5 actions, 2 hours ago --> 3 actions, etc...

I need to get the sum of actions from hour ago, 2 hours ago.....n hours ago

Any help would be appreciated

You can do It in following:

CREATE TABLE Test
(
`Id` INT,
`DateTimes` DATETIME
);    
INSERT INTO Test(Id, DateTimes) VALUES (1, '2015-06-09 10:12:12'), (2, '2015-06-09 10:13:12'), (3, '2015-06-09 09:12:12'), (4, '2015-06-09 09:15:12'), (5, '2015-06-09 08:15:10')

SELECT TIMESTAMPDIFF(HOUR,NOW(),DateTimes) * -1 AS Hours, 
       COUNT(*) AS Action 
FROM Test
GROUP BY TIMESTAMPDIFF(HOUR,NOW(),DateTimes)

OUTPUT:

Hour    Action
24        1
23        2
22        2

SQL FIDDLE

I guess the only change you need to do is to convert your HOUR to the difference between NOW and the CompDate:

SELECT HOUR( timediff( NOW( ) , CompDate) ) AS HOUR ,  COUNT( 1 ) AS action
FROM mytable
WHERE CompDate > DATE_SUB( NOW( ) , INTERVAL 24 HOUR )
GROUP BY HOUR
ORDER BY HOUR

Use Order By and Group By

SELECT HOUR(CompDate) AS hour, COUNT(1) AS action
FROM mytable
WHERE ((CompDate >= DATE_SUB(NOW(), INTERVAL 24 HOUR))
GROUP BY HOUR(CompDate) 
ORDER BY HOUR(CompDate);

Use Concat if you want to add hours ago from query itself

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM