SQL:以10分钟为增量计数调用

时间:2012-09-11 14:17:36

标签: sql datediff dateadd

我需要确定我们在这个月内以10分钟的增量进行了多少次通话。我有以下SQL查询在半小时工作,但我不能让它以10分钟为增量工作。我可能错过了一些简单的东西..任何帮助将不胜感激。感谢

select 
    count(*) as Callcount,
    case 
       when datepart(mi, PBXqtime) < 30 
          then dateadd(hh, datediff(hh, 0, PBXqtime) + 0, 0)
          else dateadd(mi, 30, dateadd(hh, datediff(hh, 0, PBXqtime) + 0, 0)) 
    end as time
from 
    callcomplete 
where 
    CustId = '3100472' 
    and PBXQTime between '11/1/11 0:0:00' and '11/30/11 23:59:00'
group by 
    case 
       when datepart(mi, PBXqtime) < 30 
        then dateadd(hh, datediff(hh, 0, PBXqtime) + 0, 0) 
        else dateadd(mi, 30, dateadd(hh, datediff(hh, 0, PBXqtime) + 0, 0)) 
    end

2 个答案:

答案 0 :(得分:1)

尚未测试,但是:

SELECT
    DATEPART(DAY, pbxqtime) AS [day], DATEPART(HOUR, pbxqtime) AS [hour], 
    (DATEPART(MINUTE, pbxqtime) / 10) AS [interval], COUNT(*) AS Callcount
FROM
    callcomplete
WHERE
    custid = '3100472'
    AND pbxqtime BETWEEN '11/1/11 0:0:00' AND '11/30/11 23:59:00'
GROUP BY
    DATEPART(DAY, pbxqtime), DATEPART(HOUR, pbxqtime), 
    (DATEPART(MINUTE, pbxqtime) / 10)

这是假设一个MSSQL环境。此外,关于如何指定日期范围,下面还有激烈的争论。有人认为使用>=<=之类的简单运算符可以更好地工作并且更清晰。因此,您也可以使用AND pbxqtime >= '2011-11-01' AND pbxqtime < '2011-12-01'

答案 1 :(得分:1)

我认为这样可行(但由于我没有您的数据而未经测试):

select 
    count(*) as Callcount,
    DATEADD(minute,(DATEDIFF(minute,'20100101',PBXQTime) / 10)*10,'20100101')
from 
    callcomplete 
where 
    CustId = '3100472' 
    and PBXQTime >= '20111101'
    and PBXQTime < '20111201'
group by 
    DATEADD(minute,(DATEDIFF(minute,'20100101',PBXQTime) / 10)*10,'20100101')

从一些固定的时间点开始,取出分钟数,除以10(将向下舍入到最接近的整数),然后乘以10并加回到相同的固定时间点。