【问题标题】:SQL Server query, most frequent in hourSQL Server 查询,一小时内最频繁
【发布时间】:2011-12-19 05:27:14
【问题描述】:

我有一个表格,我可以在其中插入页面加载。有趣的字段是进入时间和国家/地区。

如何查询,以便按小时获取最频繁的国家。结果集应如下所示(小时、国家/地区):

  • 01 - 美国
  • 02 - 新加坡
  • 03 - 印度
  • 04 - 丹麦

...等等。

我开始使用类似的东西

select DatePart(hour, entrytime) AS h, country from rpageload group by DatePart(hour, entrytime), country

但我认为我走错了方向。 ORDER BY 和 COUNT(*) 需要放在某个地方:)

-- 编辑/添加--

我发现这种方法给了我正确的结果。但我显然也得到了许多结果集,而不仅仅是一个,就像我想要的那样。

DECLARE @count INT
SET @count = 0
WHILE (@count < 24)
BEGIN
    SELECT TOP 1 @count AS hr, COUNT(*) AS nbr, country FROM rpageload WHERE DATEPART(hour, entrytime) = @count GROUP BY country ORDER BY nbr DESC
    SET @count = (@count + 1)
END

只是为了澄清:日期或日期无关紧要。目的是显示在一天中的不同时间哪个国家最频繁

【问题讨论】:

    标签: sql sql-server-2005 select group-by


    【解决方案1】:

    你快到了!

    SELECT DatePart(hour, entrytime) AS h, country
    FROM rpageload 
    GROUP BY DatePart(hour, entrytime), country
    ORDER BY COUNT(*) DESC
    

    但是,这将合并每小时每天的条目 所以昨天下午 1-2 点之间将与今天下午 1-2 点一起计算

    如果这是不希望的,您需要在 WHERE 子句中过滤掉其他日期。 或者,在时间之外按天分组

    编辑:
    实际上,我没有正确阅读问题。

    SELECT DatePart(hour, entrytime) AS h, country
    FROM rpageload rp1
    GROUP BY DatePart(hour, entrytime), country
    HAVING COUNT(*) = 
     (SELECT MAX(COUNT(*))
      FROM rpageload rp2
      WHERE DatePart(rp2.hour, rp2.entrytime) = DatePart(rp1.hour, rp1.entrytime)
      GROUP BY DatePart(hour, entrytime), country
     )
    ORDER BY h
    

    当两个或多个国家/地区的计数相同并且是该小时的最大值时会发生什么?

    或者,

    WITH RPL1 AS
    (
      SELECT DatePart(hour, entrytime) AS h, country, COUNT(*) AS cnt
      FROM rpageload rp1
      GROUP BY DatePart(hour, entrytime), country
    ),
    RPL2 AS
    (
      SELECT h, MAX(cnt) as maxcnt
      FROM RPL1
      GROUP BY h
    )
    SELECT RPL1.h, country
    FROM RPL1
    JOIN RPL2 ON RPL1.h = RPL2.h AND RPL1.cnt = RPL2.maxcnt
    

    最后两个查询将返回匹配相同最大频率的所有行。所以,同一小时可能会在结果集中出现多次。

    如果您想过滤掉这些,请查看ROW_NUMBER

    WITH RPL1 AS
    (
      SELECT DatePart(hour, entrytime) AS h, country, COUNT(*) AS cnt
      FROM rpageload rp1
      GROUP BY DatePart(hour, entrytime), country
    ),
    RPL2 AS
    (
      SELECT h, MAX(cnt) as maxcnt
      FROM RPL1
      GROUP BY h
    ),
    DUPES AS
    (
      SELECT RPL1.h, country, cnt, ROW_NUMBER() OVER(PARTITION BY RPL1.h ORDER BY country) AS rn
      FROM RPL1
      JOIN RPL2 ON RPL1.h = RPL2.h AND RPL1.cnt = RPL2.maxcnt
    )
    SELECT h, country, cnt
    FROM DUPES
    WHERE rn = 1
    

    【讨论】:

    • 但是这个结果集给了我几个具有相同“h”(小时)的列
    • 如果两个国家有相同的数字并且是最大值,只返回一个:) 我认为这将是一个罕见的巧合
    • 最后一张很棒。 (另一个在 GROUP 附近有语法错误)。我认为我们有一个赢家
    • 我刚刚编辑了另一个查询。我混淆了 WHERE 和 GROUP BY 的顺序。现在应该可以了。
    • Msg 4112, Level 15, State 1, Line 15 排名函数“ROW_NUMBER”必须有一个 ORDER BY 子句。顺便说一句,如果可能的话,我还想要实际数字(小时、国家、多少):)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-27
    • 1970-01-01
    相关资源
    最近更新 更多