Average posts per hour on MySQL?

谁都会走 提交于 2019-11-30 18:06:26

You can use a sub-query to group the data by day/hour, then take the average by hour across the sub-query.

Here's an example to give you the average count by hour for the past 7 days:

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

Aggregate the information by date and hour, and then take the average by hour:

select hour, avg(numposts)
from (SELECT date(`date`) as day, HOUR(FROM_UNIXTIME(`date`)) AS `hour`,
             count(*) as numposts
      from fb_posts
      WHERE DATE(FROM_UNIXTIME(`date`)) between <date1> and <date2>
      GROUP BY date(`date`), hour 
     ) d
group by hour
order by 1

By the way, I prefer including the explicit order by, since most databases do not order the results of a group by. Mysql happens to be one database that does.

SELECT 
    HOUR(FROM_UNIXTIME(`date`)) AS `hour`
    , COUNT(`id`) \ COUNT(DISTINCT TO_DAYS(`date`)) AS avgHourlyPostCount
FROM fb_posts 
WHERE `date` > '2012-01-01' -- your optional date criteria 
GROUP BY hour

This gives you a count of all the posts, divided by the number of days, by hour.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!