I have a data set with several time windows, an availability indicator and a priority index.
Create data set:
CREATE TABLE TimeWindows(
TimeFrom DATETIME NOT NULL,
TimeTo DATETIME NOT NULL,
Priority INT NOT NULL,
Available BIT NOT NULL
);
INSERT INTO TimeWindows(TimeFrom, TimeTo, Priority, Available) VALUES
('2017-07-22 07:00:00', '2017-07-22 12:00:00', 1, 1),
('2017-07-22 13:00:00', '2017-07-22 17:00:00', 1, 1),
('2017-07-22 12:30:00', '2017-07-23 00:00:00', 3, 0),
('2017-07-23 07:00:00', '2017-07-23 12:00:00', 1, 1),
('2017-07-23 13:00:00', '2017-07-23 17:00:00', 1, 1),
('2017-07-23 00:00:00', '2017-07-24 00:00:00', 2, 0),
('2017-07-23 19:00:00', '2017-07-23 20:00:00', 4, 1),
('2017-07-24 07:00:00', '2017-07-24 12:00:00', 1, 1),
('2017-07-24 13:00:00', '2017-07-24 17:00:00', 1, 1),
('2017-07-24 15:00:00', '2017-07-24 16:00:00', 4, 0);
Example data set:
| TimeFrom | TimeTo | Priority | Available |
|---------------------|---------------------|----------|-----------|
| 2017-07-22 07:00:00 | 2017-07-22 12:00:00 | 1 | 1 |
| 2017-07-22 13:00:00 | 2017-07-22 17:00:00 | 1 | 1 |
| 2017-07-22 12:30:00 | 2017-07-23 00:00:00 | 3 | 0 |
| 2017-07-23 07:00:00 | 2017-07-23 12:00:00 | 1 | 1 |
| 2017-07-23 13:00:00 | 2017-07-23 17:00:00 | 1 | 1 |
| 2017-07-23 00:00:00 | 2017-07-24 00:00:00 | 2 | 0 |
| 2017-07-23 19:00:00 | 2017-07-24 20:00:00 | 4 | 1 |
| 2017-07-24 07:00:00 | 2017-07-24 12:00:00 | 1 | 1 |
| 2017-07-24 13:00:00 | 2017-07-24 17:00:00 | 1 | 1 |
| 2017-07-24 15:00:00 | 2017-07-24 16:00:00 | 4 | 0 |
Problem:
I want to generate a new set of time windows, which only represent the available time slots.
Business rules:
- Time windows with a higher priority, will overrule conflicting time windows with a lower priority
- Availability indicator is set to 1 if available and is set to 0 if not available
- Overlapping time windows need to be consolidated
- An available time window which is 'split' by a period of unavailability, will be converted into two separate available time windows
Desired results:
| TimeFrom | TimeTo |
|---------------------|---------------------|
| 2017-07-22 07:00:00 | 2017-07-22 12:00:00 |
| 2017-07-23 19:00:00 | 2017-07-23 20:00:00 |
| 2017-07-24 07:00:00 | 2017-07-24 12:00:00 |
| 2017-07-24 13:00:00 | 2017-07-24 15:00:00 |
| 2017-07-24 16:00:00 | 2017-07-24 17:00:00 |
Can anyone advise me on how to solve this problem in SQL?
Thanks in advance for your help.