sql查询找到最受欢迎的小时

时间:2013-02-28 11:55:50

标签: mysql sql oracle

给出一个包含2列的表

Name(type VARCHAR) Time(type DATETIME)

我需要编写一个SQL查询来查找条目数最多的小时。

例如:

Name   Time 
----   ----
a     12:30pm
b     12:05pm
c     13:55pm
d     12:50pm
e     01:02am

期望的结果是小时:中午12点 - 下午1点

我的一般想法是:
1)按小时分组行 2)计算行/组
3)按降序排列计数
4)打印最大计数

我需要帮助将其转换为SQL查询。

2 个答案:

答案 0 :(得分:3)

这非常简单......

SELECT HOUR(Time) as Hr,COUNT(*) AS Cnt
FROM MyTable
GROUP BY Hour(Time)
ORDER BY Cnt DESC
LIMIT 1

GROUP BY Hour(Time) - 按小时分组

ORDER BY Cnt DESC - 这使得它按计数排序(按降序排列)

LIMIT 1 - 因为您只需要一个最佳结果

答案 1 :(得分:0)

这是我理解你正在寻找的Oracle版本:

SELECT t_stamp
     , MAX(count(t_stamp)) OVER (PARTITION BY t_stamp ORDER BY t_stamp)  hits_per_hr_interval
  FROM
  (
  SELECT name, EXTRACT(hour From Cast(t_stamp as timestamp)) t_stamp
    FROM stack_test
  )
  GROUP BY t_stamp
  /

  T_STAMP    HITS_PER_HR_INTERVAL
  -------------------------------
  12          3
  13          2

或使用row_number():

SELECT * FROM
(
 SELECT t_stamp
      , Count(t_stamp) OVER (PARTITION BY t_stamp ORDER BY t_stamp) hits_per_hr_interval 
      , ROW_NUMBER() OVER (PARTITION BY t_stamp ORDER BY t_stamp) hr_seq
   FROM
   (
   SELECT EXTRACT(hour From Cast(t_stamp as timestamp)) t_stamp
     FROM stack_test
   )
  )
  -- WHERE hr_seq = 1  -- optional to see only first row per group as in above example 
  /

 T_STAMP    HITS_PER_HR_INTERVAL    HR_SEQ
 ------------------------------------------
 12         3                       1
 12         3                       2
 12         3                       3
 13         2                       1
 13         2                       2

您可以添加更多过滤器,例如您的小时数在12到1之间......