I need to create a lookup table to output by minute of the day of the team who are on duty. The shift times are 09:00 - 18:00 day shift and a night shift of 18:00 - 09:00. We have 4 Teams named Red Green Blue and White, the rota is on a recurring 8 week pattern. The pattern starts on 1st April 2023 2 Days Blue 2 Nights Green, 2 Days White 2 nights Blue, 2 days Red 2 nights White, 2 days Green 2 nights Red, then repeats starting with blue days again. The pattern never changes.
| Sample | Days | WeekDay | Shifts | Wholetime_Shift |
| ------------ | ------------ | ------------ | ------------ | ------------ |
| 2023-04-01 09:00:00.000 | 0 | Saturday | B/G | B |
| 2023-04-01 10:00:00.000 | 0 | Saturday | B/G | B |
| 2023-04-01 11:00:00.000 | 0 | Saturday | B/G | B |
| 2023-04-01 12:00:00.000 | 0 | Saturday | B/G | B |
| 2023-04-01 13:00:00.000 | 0 | Saturday | B/G | B |
The issue I have is that the case statement in the query is written based on a 2,2,3,2 pattern.
Any help would be most appreciated.
;WITH samples as (
select Cast( '04-01-2023 09:00' as DateTime ) as Sample
union all
/* Add hours up to the desired end date. */
select DateAdd( hour, 1, Sample )
from Samples
where Sample <= '2026-01-01'
), ExtendedSamples as (
/* Calculate the number of days since the beginning of the first shift on 1/1/2013. */
select Sample, DateDiff( hour, '04-01-2023 09:00', Sample ) / 24 as Days
from Samples
), Shifts as (
/* Calculate the shifts for each day. */
select *, case when (Days+1) % 9 in (1,2 ) then 'B/G' when (Days+1) % 9 in (3,4) then 'W/B' WHEN (Days+1) % 9 IN (5,6) THEN 'R/W' WHEN (Days+1) % 9 IN (7,8) THEN 'G/R' end as Shifts
from ExtendedSamples
)
SELECT Sample, days, DATENAME(WEEKDAY,Sample) WeekDay,Shifts,
case when DatePart( hour, Sample ) between 9 and 17 then Substring( Shifts, 1, 1 ) else Substring( Shifts, 3, 1 ) end as Wholetime_Shift
FROM Shifts
option ( maxrecursion 0 );
1条答案
按热度按时间wfauudbj1#
Based on your description, the following may get you closer to where you need to be.