most active time of day based on start and end time

后端 未结 7 1620
悲哀的现实
悲哀的现实 2021-02-08 06:53

I\'m logging statistics of the gamers in my community. For both their online and in-game states I\'m registering when they \"begin\" and when they \"end\". In order to show the

7条回答
  •  孤街浪徒
    2021-02-08 07:19

    The easiest solution is to run a cron at the top of each hour of who has a start time but no end time (null end time? if you reset it when they login) and log that count. This will give you a count of currently logged in at each hour without needing to do funky schema changes or wild queries.

    Now when you check the next hour and they had logged out they would fall out of your results. This query would work if you reset end time when they login.

    SELECT CONCAT(CURDATE(), ' ', HOUR(NOW()), ' ', COUNT(*)) FROM activity WHERE DATE(start) = CURDATE() AND end IS NULL;

    Then you can log this at your hearts content to a file or to another table (Of course you might need to adjust the select per your log table). For example you can have a table that gets one entry per day and only gets updated once.

    Assume a log table like:

    current_date | peak_hour | peak_count

    SELECT IF(peak_count< $peak_count, true, false) FROM log where DATE(current_date) = NOW();
    

    where $peak_count is a variable coming from your cron. If you find that you have a new bigger peak count you do an update, if the record does not exist for the day do an insert into log. Otherwise, no you have not beat a peak_hour from earlier in the day, don't do an update. This means each day will give you only 1 row in your table. Then you don't need to do any aggregation, it is all right there for you to see the date and hour over the course of a week or month or whatever.

提交回复
热议问题