我需要获取过去24小时的记录,但不能像这样分组:
SELECT HOUR(CompDate) AS hour, COUNT(1) AS action
FROM mytable
WHERE ((CompDate >= DATE_SUB(NOW(), INTERVAL 24 HOUR))
GROUP BY `hour`;
以上查询会告诉我:第22小时 - > 6个动作,第21小时 - > 9个动作。
我想要的是:1小时前 - > 5个动作,2个小时前 - > 3个行动等......
我需要从小时前,2小时前... n小时前得到行动的总和
任何帮助将不胜感激
答案 0 :(得分:1)
你可以在下面这样做:
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)
<强>输出:强>
Hour Action
24 1
23 2
22 2
<强> SQL FIDDLE 强>
答案 1 :(得分:0)
我想您需要做的唯一改变就是将您的HOUR转换为NOW和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
答案 2 :(得分:0)
使用Order By和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);
如果您想在几个小时之前从查询中添加
,请使用Concat