I have a temp table containing 24 entries, one for each hour of a specific day annotated by DayID. The table contains an indication whether an application is on or off during that specific time range.
I would like to reduce the number of entries in the table to only show the times during which the application should be on.
Some sample data follows:
CREATE TABLE #OnOff
(
RowID INT identity(1, 1),
DayID TINYINT,
OnOff BIT,
StartTime TIME,
EndTime TIME
)
INSERT INTO #OnOff (DayID, OnOff, StartTime, EndTime) VALUES
(1, 0, '00:00', '00:59'),
(1, 0, '01:00', '01:59'),
(1, 0, '02:00', '02:59'),
(1, 1, '03:00', '03:59'),
(1, 1, '04:00', '04:59'),
(1, 0, '05:00', '05:59'),
(1, 1, '06:00', '06:59'),
(1, 1, '07:00', '07:59'),
(1, 0, '08:00', '08:59'),
(1, 0, '09:00', '09:59'),
(1, 0, '10:00', '10:59'),
(1, 0, '11:00', '11:59'),
(1, 0, '12:00', '12:59'),
(1, 0, '13:00', '13:59'),
(1, 1, '14:00', '14:59'),
(1, 1, '15:00', '15:59'),
(1, 1, '16:00', '16:59'),
(1, 0, '17:00', '17:59'),
(1, 0, '18:00', '18:59'),
(1, 0, '19:00', '19:59'),
(1, 0, '20:00', '20:59'),
(1, 0, '21:00', '21:59'),
(1, 0, '22:00', '22:59'),
(1, 0, '23:00', '23:59')
The desired output should be
DayID StartTime EndTime
1 03:00 04:59
1 06:00 07:59
1 14:00 16:59
The #OnOff table will always contain a value for every hour of the day (ie end and start times will always be consecutive, except for the last hour). One can obviously achieve this with a cursor, but this seems quite inefficient. Is there a better way to achieve this result.