在SQL中计算分钟之间的适当时差

时间:2017-02-02 10:14:01

标签: sql date sql-server-2012

我需要计算从几分钟到15:00到16:00的时间差。如果callend超过16:00:00,那么我不想在15:00到16:00之间计算它,它应该在16:00到17:00之间计算

我使用以下查询在SQL中计算

select SUM(datediff(second, callstart, callend))diff from tablex where    
CAST(callstart as TIME) BETWEEN '15:00:00' AND '16:00:00'

我收到了结果

diff
14

但我需要结果4.如果callstart和callend在15:58到16:09之间,那么我需要将特定的超时时间带到下一列,如diff16to17。例如,我需要将从15:58到16:09的时间延长9分钟到diff16to17列

这是我的表

    callstart                    callend
 2017-02-01 15:59:38.997    2017-02-01 16:09:39.833
 2017-02-01 15:56:47.720    2017-02-01 15:59:38.527
 2017-02-01 15:55:23.573    2017-02-01 15:56:47.207

2 个答案:

答案 0 :(得分:1)

您只需在WHERE

中将条件包含在callend中
WHERE CAST(callstart as TIME) BETWEEN '15:00:00' AND '16:00:00'
  AND CAST(callend as TIME) < '16:00:00'

如果这是一个基于时间的计费计算,您需要弄清楚呼叫持续超过一小时的情况的要求是什么,因为现在它们不会包含在任何总和中

而是将小时窗口中发生的分钟数相加,例如

WITH window AS
(    SELECT CASE WHEN CAST(callstart as TIME) < '15:00:00' THEN '15:00:00' ELSE callstart END as windowstart, 
            CASE WHEN CAST(callend as TIME) > '16:00:00' THEN '16:00:00' ELSE callend END as windowend
    FROM tablex
    WHERE CAST(callstart as TIME) < '16:00:00' AND CAST(callend as TIME) > '15:00:00'
)
SELECT SUM(datediff(second, windowstart, windowend)) as diff FROM window

答案 1 :(得分:1)

如果我做对了

select sum(datediff(second,
                 case when CAST(callend as TIME) >='16:00:00'
                 then '16:00:00' else CAST(callstart as TIME) end
                 , CAST(callend as TIME)))  diff 

from (
    -- example data
    values
     ('2017-02-01 15:59:38.997','2017-02-01 16:09:39.833'),
     ('2017-02-01 15:56:47.720','2017-02-01 15:59:38.527'),
     ('2017-02-01 15:55:23.573','2017-02-01 15:56:47.207')
    )tablex(callstart, callend)

where    
CAST(callstart as TIME) BETWEEN '15:00:00' AND '16:00:00';