most active time of day based on start and end time

后端 未结 7 1625
悲哀的现实
悲哀的现实 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:43

    @rsanchez had an amazing answer, but the query for most active time of day has a weird behaviour when handling session times that started and ended on the same hour (a short session). The query seems to calculate them to last for 24 hours.

    With trial and error I corrected his query from that part to be following

    SELECT hour, count(*) AS activity
    FROM steamonlineactivity, hour
    WHERE ( hour >= HOUR(online) AND hour <= HOUR(offline)
      OR HOUR(online) > HOUR(offline) AND HOUR(online) <= hour
      OR HOUR(offline) >= hour AND HOUR(offline) < HOUR(online) )
    GROUP BY hour
    ORDER BY activity DESC;
    

    So with following structure:

    CREATE TABLE hour ( hour tinyint not null, primary key(hour) );
    INSERT hour (hour)
    VALUES (0), (1), (2), (3), (4), (5), (6), (7), (8), (9), (10)
     , (11), (12), (13), (14), (15), (16), (17), (18), (19), (20)
     , (21), (22), (23);
    
    CREATE TABLE `steamonlineactivity` (
      `activityID` int(13) NOT NULL AUTO_INCREMENT,
      `userID` varchar(255) NOT NULL,
      `online` datetime DEFAULT NULL,
      `offline` datetime DEFAULT NULL,
      PRIMARY KEY (`activityID`)
    );
    
    INSERT INTO `steamonlineactivity` (`activityID`, `userID`, `online`, `offline`) VALUES
    (1, '1',    '2014-01-01 16:01:00',  '2014-01-01 19:01:00'),
    (2, '2',    '2014-01-02 16:01:00',  '2014-01-02 19:01:00'),
    (3, '3',    '2014-01-01 22:01:00',  '2014-01-02 02:01:00'),
    (4, '4',    '2014-01-01 16:01:00',  '2014-01-01 16:05:00');
    

    The top query to get the most active times output following:

    +------+----------+
    | hour | activity |
    +------+----------+
    |   16 |        3 |
    |   17 |        2 |
    |   18 |        2 |
    |   19 |        2 |
    |   22 |        1 |
    |   23 |        1 |
    |    0 |        1 |
    |    1 |        1 |
    |    2 |        1 |
    +------+----------+
    

    Instead of the original query which gives following erronous result:

    +------+----------+
    | hour | activity |
    +------+----------+
    |   16 |        3 |
    |   17 |        3 |
    |   18 |        3 |
    |   19 |        3 |
    |    0 |        2 |
    |    1 |        2 |
    |    2 |        2 |
    |   22 |        2 |
    |   23 |        2 |
    |   11 |        1 |
    |   12 |        1 |
    |   13 |        1 |
    |   14 |        1 |
    |   15 |        1 |
    |    3 |        1 |
    |    4 |        1 |
    |   20 |        1 |
    |    5 |        1 |
    |   21 |        1 |
    |    6 |        1 |
    |    7 |        1 |
    |    8 |        1 |
    |    9 |        1 |
    |   10 |        1 |
    +------+----------+
    
    0 讨论(0)
提交回复
热议问题