SQL Server Tracking Scheduled Shifts when the day varies

后端 未结 2 1099
傲寒
傲寒 2021-01-16 05:30

I\'m not even sure where to start in solving this one, I need to query production data from our MS SQL 2012 Db that has a datetime stamp based on the shift it was recorded i

相关标签:
2条回答
  • 2021-01-16 06:00

    I'm sure it will get even tricker when there is a holiday or a shutdown occurs. You are thinking like a programmer, you are thinking there is an algorithm that can determine your answer. Instead, if would advise that you think like a data-guy. There should be a source of information somewhere that has the answer you seek. Ask the person who sets up the schedule if he knows. There should be a table somewere that tells you what shifts are assigned to what time slots. Use the data it contains to get your answer.

    0 讨论(0)
  • 2021-01-16 06:03

    The following cranks out a table of shifts. It isn't exactly clear what you want to do, but you should be able to reverse engineer determining the shift from the date/time of an event using some of the calculations shown here.

    EDIT: Corrected case to handle to 2/2/3/2 pattern.

    ; with Samples as (
      -- Start at the beginning of 2013.
      select Cast( '01-01-2013 00:00' as DateTime ) as Sample
      union all
      -- Add hours up to the desired end date.
      select DateAdd( hour, 1, Sample )
        from Samples
        where Sample <= '2013-01-30'
      ),
      ExtendedSamples as (
      -- Calculate the number of days since the beginning of the first shift on 1/1/2013.
      select Sample, DateDiff( hour, '01-01-2013 07:00', Sample ) / 24 as Days
        from Samples ),
      Shifts as (
      -- Calculate the shifts for each day.
      select *,
        case when ( Days + 1 ) % 9 in ( 0, 1, 4, 5 ) then 'C/D' else 'A/B' end as Shifts
        from ExtendedSamples )
      select *,
        case when DatePart( hour, Sample ) between 7 and 18 then Substring( Shifts, 1, 1 ) else Substring( Shifts, 3, 1 ) end as Shift
        from Shifts
        option ( maxrecursion 0 )
    
    0 讨论(0)
提交回复
热议问题