SQL: generate schedule table with different frequencies

I am working in SQL Server 2012. I have 3 tables. The first is the "schedule" table. Its structure is similar:

CREATE TABLE schedule
(
    JobID int
    ,BeginDate date
    ,EndDate date
)

      

Some examples of data:

INSERT INTO schedule
SELECT 1, '2017-01-01', '2017-07-31' UNION ALL
SELECT 2, '2017-02-01', '2017-06-30'

      

The second is "frequency". Its structure is similar:

CREATE TABLE frequency
(
    JobID int
    ,RunDay varchar(9)
)

      

Some examples of data:

INSERT INTO frequency
SELECT 1, 'Sunday' UNION ALL
SELECT 1, 'Monday' UNION ALL
SELECT 1, 'Tuesday' UNION ALL
SELECT 1, 'Wednesday' UNION ALL
SELECT 1, 'Thursday' UNION ALL
SELECT 1, 'Friday' UNION ALL
SELECT 1, 'Saturday' UNION ALL
SELECT 2, 'Wednesday'

      

The third is the calendar table. Its structure is similar:

CREATE TABLE calendar
(
    CalendarFullDate date
    ,DayName varchar(9)
)

      

My goal is to "expand" the schedule table so that I create a row for each date spanning the date range in the BeginDate and EndDate for each job ID. The lines must correspond to the days in the frequency table for the JobID.

Until now, the date frequencies for each job have been either daily or weekly. To do this, I use the following SQL to create the desired table:

SELECT
    s.JobID
    ,c.CalendarFullDate
FROM
    schedule AS s
INNER JOIN
    calendar AS c
ON
    c.CalendarFullDate BETWEEN s.BeginDate AND s.EndDate
INNER JOIN
    frequency AS f
ON
    f.JobID = s.JobID
    AND f.RunDay = c.DayName

      

This does not work for frequencies that are higher than weekly (eg biweekly). To do this, I know that my frequency table will need to be restructured. Specifically, I will need to add a column that gives the frequency (e.g. daily, weekly, biweekly). And, I'm pretty sure I will need to add week number columns to the calendar table.

How can I create my desired table to accommodate at least 2 week frequencies (if not higher frequencies)? For example, if JobID = 3 is a two week job that runs on Wednesday and it is associated with BeginDate = '2017-06-01' and EndDate = '2017-07-31', then for this job I would end up with the following:

JobID    Date
3        2017-06-07
3        2017-06-21
3        2017-07-05
3        2017-07-19

      

+3


source to share





All Articles