SQL DateDiff advanced usage?

前端 未结 6 1538
慢半拍i
慢半拍i 2020-12-19 19:26

I need to calculate the DateDiff (hours) between two dates, but only during business-hours (8:30 - 16:00, no weekends). This result will then be put into the Reaction_Time c

6条回答
  •  情深已故
    2020-12-19 20:00

    This function will give you the difference in business hours between two given times. This will return the difference in minutes or hours based on the date part parameter.

    CREATE FUNCTION [dbo].[fnBusinessHoursDateDiff] (@StartTime SmallDatetime, @EndTime SmallDateTime, @DatePart varchar(2)) RETURNS DECIMAL (10,2)
    AS 
    BEGIN
    
    DECLARE @Minutes        bigint
        ,   @FinalNumber    Decimal(10,2)
    
    -- // Create Minute By minute table for CTE
    -- ===========================================================
    ;WITH  cteInputHours (StartTime, EndTime, NextTime) AS (
        SELECT  @StartTime  
            ,   @EndTime    
            ,   dateadd(mi, 1, @StartTime)
     ),
     cteBusinessMinutes (TimeOfDay, [isBusHour], NextTime) AS(
        SELECT  StartTime [TimeOfDay]
            ,   case when datepart(dw, StartTime) between 2 and 6 and convert(time,StartTime) between '08:30' and '15:59' then 1 else 0 end [isBusHour]
            ,   dateadd(mi, 1, @StartTime)  [NextTime]
        FROM    cteInputHours
        UNION ALL
        SELECT  dateadd(mi, 1, (a.TimeOfDay)) [TimeOfDay]
            ,   case when datepart(dw, a.TimeOfDay) between 2 and 6 and  convert(time,dateadd(mi, 1, (a.TimeOfDay)) ) between '08:30' and '15:59' then 1 else 0 end [isBusHour]
            ,   dateadd(mi, 2, (a.TimeOfDay)) NextTime
        FROM    cteBusinessMinutes a
        WHERE   dateadd(mi, 1, (a.TimeOfDay)) < @EndTime
    ) 
    SELECT  @Minutes = count(*)
    FROM    cteBusinessMinutes
    WHERE   isBusHour = 1
    OPTION (MAXRECURSION 0);
    
    -- // Final Select
    -- ===========================================================
    SELECT  @FinalNumber = @Minutes / (case when @DatePart = 'hh' then 60.00 else 1 end)
    
    RETURN @FinalNumber 
    
    END
    

提交回复
热议问题