5

考虑下表,其中包含字段 - 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。

想法?

4

5 回答 5

7

要获得最受欢迎的时间,请使用此查询

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;
于 2010-03-18T16:39:54.010 回答
4

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

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 秒)。

于 2010-03-18T16:54:40.800 回答
3

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

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

于 2010-03-18T16:36:45.573 回答
3

我喜欢西蒙和彼得的答案,但我不能同时选择接受。我将 2 结合起来进行了更简洁的查询,该查询仅返回了流行的时间(我不需要计数)。

SELECT hour(date_created) AS h 
FROM my_table 
GROUP BY h 
ORDER BY count(*) DESC 
LIMIT 1
于 2010-03-18T17:28:37.080 回答
0

你可以试试这个:

SELECT 
  DATE_FORMAT(date,'%H') as hours, 
  count(*) as count 
FROM 
  myTable 
GROUP BY 
  hours 
ORDER BY 
  count DESC
于 2010-03-18T16:39:04.277 回答