Using SQL Server 2008 R2 we are looking for a way to select the shift hours that an employee has that are during the night which in the this case 22.00 and 6.00 +1.
Our problem becomes how to get the hours when the shift crosses midnight or how we get the overlap when a shift begins 05.30 to 22.30 and has an overlap in both the beginning and end of the shift.
Here is an example, theses are the data available in the database and the result we are looking for:
startDateTime | endDateTime | nightHours
--------------------------+---------------------------+----------------
2012-07-04 05:00:00.000 2012-07-04 23:00:00.000 2
2012-07-04 18:00:00.000 2012-07-05 05:00:00.000 7
Does anyone have an example or a few good pointer that we can use.
This may be overly complex, but it does work. We use a number of CTEs to construct useful intermediate representations:
Result:
You’ll note that I had to add an
IDcolumn in order to get my correlation to work.The
StartCTE finds the earliest applicable midnight. TheEndCTE finds the last time for which we need to find overlapping nights. Then, the recursiveNightsCTE computes every night between those two points in time. We then join this back to the original table (inOverlaps) to find those periods in each night which apply. Finally, inTotals, we compute how many hours each overlapping period contributed.This should work for multi-day events. You might want to change the
TotalsCTE to use minutes, or apply some other rounding functions, if you need to count partial hours.