MySQL每小时​​平均发布一次?

Dan*_*tti 11 mysql sql relational-database

我有很多帖子保存在MySQL的InnoDB表中.该表具有"id","date","user","content"列.我想制作一些统计图表,所以我最终使用以下查询来获取昨天每小时的帖子数量:

SELECT HOUR(FROM_UNIXTIME(`date`)) AS `hour`, COUNT(date)  from fb_posts 
WHERE DATE(FROM_UNIXTIME(`date`)) = CURDATE() - INTERVAL 1 DAY GROUP BY hour
Run Code Online (Sandbox Code Playgroud)

这将输出以下数据:

表数据

我可以编辑此查询以获得我想要的任何一天.但我现在想要的是每天每小时的平均值,所以如果在第1天00点我有20个帖子,在第2天00点我有40个,我希望输出为"30".如果有可能,我希望能够选择日期.

提前致谢!

Ike*_*ker 6

您可以使用子查询按天/小时对数据进行分组,然后在子查询中按小时计算.

这是一个示例,为您提供过去7天的平均小时数:

select the_hour,avg(the_count)
from
(
  select date(from_unixtime(`date`)) as the_day,
    hour(from_unixtime(`date`)) as the_hour, 
    count(*) as the_count
  from fb_posts
  where `date` >= unix_timestamp(current_date() - interval 7 day)
  and created_on < unix_timestamp(current_date())
  group by the_day,the_hour
) s
group by the_hour
Run Code Online (Sandbox Code Playgroud)