【问题标题】:MySQL: Getting "busiest" or "most popular" hour from a datetime field?MySQL:从日期时间字段中获取“最繁忙”或“最受欢迎”的时间?
【发布时间】:2010-03-18 16:25:51
【问题描述】:

考虑下表,其中包含字段 - id (int) 和 date_created (datetime):

id       date_created

 1       2010-02-25 12:25:32
 2       2010-02-26 13:40:37
 3       2010-03-01 12:02:22
 4       2010-03-01 12:10:23
 5       2010-03-02 10:10:09
 6       2010-03-03 12:45:03

我想知道这组数据一天中最繁忙/最受欢迎的时间。在此示例中,我要查找的结果是 12。

想法?

【问题讨论】:

    标签: mysql datetime count popularity


    【解决方案1】:

    要获取最受欢迎的时段,请使用此查询

    select date_format( date_created, '%H' ) as `hour`
      from [Table]
     group by date_format( date_created, '%H' )
     order by count(*) desc
     limit 1;
    

    如果您想查看所有数据,请使用这个

    select count(*) as num_records
         , date_created
         , date_format( date_created, '%H' ) as `hour`
      from [Table]
     group by `hour`
     order by num_records desc;
    

    【讨论】:

    • 使用 date_format() 比使用 hour() 有什么好处,反之亦然?
    • 不,我不这么认为。这只是我已经熟悉的功能。
    • 这与我使用 hour() 的原因相同。
    【解决方案2】:

    如果您想要更灵活一点的东西,可能是半小时或一刻钟,您可以执行以下操作:

    SELECT floor(time_to_sec(date_created)/3600),count(*) AS period 
    FROM table GROUP BY period ORDER BY c DESC
    

    如果您想要最流行的 2 小时间隔,请使用 7200。最流行的 15 分钟间隔,请使用 900。您只需要记住您处理的是秒数(一小时 3600 秒)。

    【讨论】:

    • 这会引发错误,因为 interval 是一个比较函数 (dev.mysql.com/doc/refman/5.0/en/…)。将单词 interval 更改为 foo 有效,但结果不正确。
    • 当然,忘记间隔。我忽略了计数,所以它无法正确排序(哎呀)。
    • @k00k:上面查询的错误很简单。第二个选择COUNT(*)有两个别名,这是个问题。将别名“句点”移动到第一个选定字段,因此一个有“c”,一个有“句点”。
    • @BrentBaisley,您的 COUNT(*) 有两个别名错误。
    【解决方案3】:

    使用hour() 函数提取小时,然后进行通常的聚合:

    SELECT count(hour(date_created)) AS c, hour(date_created) AS h FROM table GROUP BY h ORDER BY c DESC;

    【讨论】:

      【解决方案4】:

      我喜欢 Simon 和 Peter 的答案,但我不能同时选择接受。我将 2 结合起来进行更简洁的查询,该查询仅返回热门时段(我不需要计数)。

      SELECT hour(date_created) AS h 
      FROM my_table 
      GROUP BY h 
      ORDER BY count(*) DESC 
      LIMIT 1
      

      【讨论】:

        【解决方案5】:

        你可以试试这个:

        SELECT 
          DATE_FORMAT(date,'%H') as hours, 
          count(*) as count 
        FROM 
          myTable 
        GROUP BY 
          hours 
        ORDER BY 
          count DESC
        

        【讨论】:

          猜你喜欢
          • 2017-04-20
          • 1970-01-01
          • 2021-11-30
          • 2021-10-18
          • 2011-05-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多