汇总每小时最近12小时的数据库值

时间:2016-04-12 18:36:56

标签: mysql

我有一个包含列id,type,value,created_at的表,我想用一个查询总结最近12个小时。结果应该是每小时前的一个数组。

目前我使用此查询来获取一小时的数据:

select sum(`value`) as aggregate from `clan_values` where `type` = '2' and `created_at` between '2016-04-12 10:00:00' and '2016-04-12 10:59:59'

我没有任何线索如何只用一个查询来解决这个问题。

谢谢。

2 个答案:

答案 0 :(得分:1)

您可以按DATE_FORMAT%H

尝试分组
select sum(`value`) as aggregate 
from `clan_values` 
where `type` = '2' and `created_at` between '2016-04-12 10:00:00' and '2016-04-12 10:59:59'
group by DATE_FORMAT( `created_at`,'%H');

答案 1 :(得分:1)

您可以尝试使用此查询,它会返回最近12小时的总和(值),包括current_timestamp()的小时。如果某个小时没有行,那么您将获得该小时聚合的零。

SELECT sum(IFNULL(`value`,0)) as aggregate,
       MyTime.MyHour,
       DATE_ADD(DATE(created_at),
                  INTERVAL HOUR(created_at) hour) as ActualHour
FROM
  (SELECT DATE_ADD(DATE(CURRENT_TIMESTAMP()),
                  INTERVAL HOUR(CURRENT_TIMESTAMP())-hour.count hour) as MyHour
  FROM
  (SELECT 0 as count
  UNION SELECT 1
  UNION SELECT 2
  UNION SELECT 3
  UNION SELECT 4
  UNION SELECT 5
  UNION SELECT 6
  UNION SELECT 7
  UNION SELECT 8
  UNION SELECT 9
  UNION SELECT 10
  UNION SELECT 11)AS Hour
   )as MyTime LEFT JOIN
   `clan_values` ON DATE_ADD(DATE(created_at),INTERVAL HOUR(created_at) hour) = MyTime.MyHour
AND `type` = '2'
GROUP BY MyTime.MyHour,ActualHour
ORDER BY MyTime.MyHour ASC

sqlfiddle