考虑一个名为'Calls'的表,除其他外,包含以下列:
CalledNumber | CallBegin
-----------------------------------
004401151234567|10/08/2013 09:06:53
004303111238493|15/09/2013 14:56:29
依旧......
如何选择在日期范围内平均保持最高行数的小时?目标是在一年内找到每个季度的“忙时”。 SQL真的不是我的强项,我正在考虑有时操纵高达9.6万行,但执行时间不是关键问题。
答案 0 :(得分: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
工作DEMO
答案 1 :(得分:0)
您可以使用DATEPART()
和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))
答案 2 :(得分:0)
使用DATEPART。即,
SELECT DATEPART(hh, CallBegin) ,
COUNT(1) as callCount
FROM Calls
GROUP BY DATEPART(hh, CallBegin)
ORDER BY callCount DESC
答案 3 :(得分:0)
而不是datePart
,请尝试使用DateAdd()
和DateDiff()
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