SQL DateDiff advanced usage?

前端 未结 6 1530
慢半拍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 19:41

    Assuming you have a reference-table of the working days (and their hours), then I would use a 3 stage approach (pseudo-sql)

    (first preclude the "all in one day" trivial example, since that simplifies the logic)

     -- days that are neither the start nor end (full days)
     SELECT @FullDayHours = SUM(day start to day end)
     FROM   reference-calendar
     WHERE  Start >= midnight-after-start and End <= midnight-before-end
    
     -- time after the [query start] to the end of the first working day
     SELECT @FirstDayHours = [query start] to day end
     FROM   reference-calandar
     WHERE  start day
    
     -- time from the start of the last working day to the [query end]
     SELECT @LastDayHours = day start to [query end]
     FROM   reference-calendar
     WHERE  end-day
    
     IF @FirstDayHours < 0 SET @FirstDayHours = 0 -- starts outside working time
     IF @LastDayHours < 0 SET @LastDayHours  = 0 -- ends outside working time
    
     PRINT @FirstDayHours  + @FullDayHours + @LastDayHours
    

    Obviously it is a bit hard to do properly without more context...

提交回复
热议问题