0

考虑一个名为“呼叫”的表,其中包含以下列:

  CalledNumber | CallBegin
-----------------------------------
004401151234567|10/08/2013 09:06:53
004303111238493|15/09/2013 14:56:29

等等...

如何选择在一个日期范围内平均拥有最多行数的小时?目标是找到一年中每个季度的“忙碌时间”。SQL 在这里真的不是我的强项,我有时会考虑处理多达 960 万行,尽管执行时间不是关键问题。

4

4 回答 4

3

DATEPART是你要找的:

SELECT
    DATEPART(hour, CallBegin), COUNT(*) as NumberOfCalls
FROM
    Test
WHERE
    CallBegin BETWEEN '2013-01-01' AND '2013-12-31'
GROUP BY
    DATEPART(hour, CallBegin)
ORDER BY
    NumberOfCalls DESC

工作演示

于 2013-09-10T18:54:10.227 回答
0

您可以使用DATEPART()and CONVERT(),我假设 CallBegin 不存储为日期时间:

SELECT  YEAR(CONVERT(DATETIME,CallBegin,103))'Year'
      , DATEPART(quarter,CONVERT(DATETIME,CallBegin,103))'Quarter'
      , DATEPART(hour,CONVERT(DATETIME,CallBegin,103))'Hour'
      , COUNT(*)
FROM Calls
GROUP BY YEAR(CONVERT(DATETIME,CallBegin,103))
       , DATEPART(quarter,CONVERT(DATETIME,CallBegin,103))
       , DATEPART(hour,CONVERT(DATETIME,CallBegin,103))

如果您想跨越年份,只需消除年份部分:

SELECT  DATEPART(quarter,CONVERT(DATETIME,CallBegin,103))'Quarter'
      , DATEPART(hour,CONVERT(DATETIME,CallBegin,103))'Hour'
      , COUNT(*)
FROM Calls
GROUP BY DATEPART(quarter,CONVERT(DATETIME,CallBegin,103))
       , DATEPART(hour,CONVERT(DATETIME,CallBegin,103))
于 2013-09-10T18:55:15.273 回答
0

使用DATEPART。IE,

SELECT  DATEPART(hh, CallBegin) ,
    COUNT(1) as callCount
FROM Calls
GROUP BY DATEPART(hh, CallBegin)
ORDER BY callCount DESC
于 2013-09-10T18:55:20.463 回答
0

而不是datePart,尝试使用DateAdd()andDateDiff()

  Select top 1 DateAdd(hour, DateDiff(hour, 0, CallBegin), 0)
  From Calls
  Group By DateAdd(hour, DateDiff(hour, 0, CallBegin), 0) 
  Order By Count(*) Desc

这将表现得更好,因为它是纯算术的,即不解析日期和/或日期时间的文本表示。

添加计数以查看该小时内发生了多少

  Select top 1 DateAdd(hour, DateDiff(hour, 0, CallBegin), 0), Count(*)
  From Calls
  Group By DateAdd(hour, DateDiff(hour, 0, CallBegin), 0) 
  Order By Count(*) Desc
于 2013-09-10T19:04:13.937 回答