获取一天中的一段时间的总秒数

时间:2018-01-08 15:51:43

标签: sql sql-server

我遇到了这个问题:对于不同的转弯,我需要计算一个劳动时间的秒数,除了间隔时间。

所以,我有这张桌子:

cdLaborTime nmLaborTime beginLaborTime endLaborTime beginInterval endInterval
----------- ----------- -------------  ------------ ------------- --------------
1           1st Turn    07:30          16:45        11:00         12:00
2           2nd Turn    16:45          01:30        20:00         21:00

主要问题:有时候我们会在一天内开始轮流,并在第二天结束。

我创建了这个视图来帮助我:

CREATE VIEW v_LaborTime
AS

SELECT CASE 
        WHEN CAST(beginLaborTime AS TIME) < CAST(endLaborTime AS TIME)
            THEN DATEDIFF(SECOND, beginLaborTime, endLaborTime) - DATEDIFF(SECOND, beginInterval, endInterval)
        ELSE (DATEDIFF(SECOND, beginLaborTime, '23:59') + DATEDIFF(SECOND, '00:00', endLaborTime)) - DATEDIFF(SECOND, beginInterval, endInterval)
        END AS TotalSeconds

        , CASE 
        WHEN CAST(beginLaborTime AS TIME) < CAST(GETDATE() AS TIME) AND CAST(beginInterval AS TIME) < CAST(GETDATE() AS TIME) AND CAST(GETDATE() AS TIME) > endInterval
            THEN DATEDIFF(SECOND, beginLaborTime, CAST(GETDATE() AS TIME)) - DATEDIFF(SECOND, beginInterval, endInterval)
        WHEN CAST(beginLaborTime AS TIME) < CAST(GETDATE() AS TIME) AND CAST(beginInterval AS TIME) < CAST(GETDATE() AS TIME)
            THEN DATEDIFF(SECOND, beginLaborTime, CAST(GETDATE() AS TIME)) - DATEDIFF(SECOND, beginInterval, CAST(GETDATE() AS TIME))
        WHEN CAST(beginLaborTime AS TIME) < CAST(GETDATE() AS TIME) AND CAST(beginInterval AS TIME) > CAST(GETDATE() AS TIME)
            THEN DATEDIFF(SECOND, beginLaborTime, CAST(GETDATE() AS TIME))
        WHEN CAST(beginLaborTime AS TIME) > CAST(GETDATE() AS TIME) AND CAST(beginInterval AS TIME) < CAST(GETDATE() AS TIME) AND CAST(GETDATE() AS TIME) > endInterval
            THEN (DATEDIFF(SECOND, beginLaborTime, '23:59') + DATEDIFF(SECOND, '00:00', CAST(GETDATE() AS TIME))) - DATEDIFF(SECOND, beginInterval, endInterval)
        WHEN CAST(beginLaborTime AS TIME) > CAST(GETDATE() AS TIME) AND CAST(beginInterval AS TIME) < CAST(GETDATE() AS TIME)
            THEN (DATEDIFF(SECOND, beginLaborTime, '23:59') + DATEDIFF(SECOND, '00:00', CAST(GETDATE() AS TIME))) - DATEDIFF(SECOND, beginInterval, CAST(GETDATE() AS TIME))
        ELSE (DATEDIFF(SECOND, beginLaborTime, '23:59') + DATEDIFF(SECOND, '00:00', CAST(GETDATE() AS TIME)))
        END AS CurrentSeconds

        ,CASE 
        WHEN CAST(GETDATE() AS TIME) >= beginLaborTime AND (CAST(GETDATE() AS TIME) < endLaborTime OR (beginLaborTime > endLaborTime))
            THEN 'OPEN'
        ELSE
            'CLOSE'
        END AS 'cdState'
        , cdLaborTime
        , nmLaborTime
        , beginLaborTime
        , endLaborTime
        , beginInterval
        , endInterval
FROM [laborTime]

它有效,但它太大而且奇怪,有没有更好的方法来解决这个问题?

0 个答案:

没有答案