SQL Server counting hours between dates excluding Fri 6pm - Mon 6am

前端 未结 2 1846
离开以前
离开以前 2021-01-14 21:47

I am looking for a SQL server function which can count the number of hours between 2 given datetime values, but excludes the hours between 6pm on Friday and 6am on Monday. <

2条回答
  •  孤城傲影
    2021-01-14 22:19

    This uses a number table. Adjust weekend start/end in parmeters:

    declare @d1 as datetime = '2018-06-01 05:30:00'
        , @d2 as datetime = '2018-06-18 19:45:00'
        , @FridayWE as int = 18 --6pm
        , @MondayWS as int = 6  --6am
    
    ;WITH x AS (SELECT n FROM (VALUES (0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) v(n))
    select count(*) as HoursBetweenDatetimes
    from (
        SELECT dateadd(hour, ones.n + 10*tens.n + 100*hundreds.n + 1000*thousands.n, dateadd(hour, datediff(hour, 0, @d1), 0)) as [DateHour]
        FROM x ones,     x tens,      x hundreds,       x thousands
        ) a
    where not ((DATEPART(dw,[DateHour]) = 6 and DATEPART(hour,[DateHour]) >= @FridayWE)
    or (DATEPART(dw,[DateHour]) = 7 )
    or (DATEPART(dw,[DateHour]) = 1 )
    or (DATEPART(dw,[DateHour]) = 2 and DATEPART(hour,[DateHour]) < @MondayWS))
    and [DateHour] < @d2
    

提交回复
热议问题