I have a table like this:
create table time_sheet
(
StatusCode char(1),
start_time datetime,
end_time datetime
)
insert into time_sheet values
('W','2012-08-01 10:00:00','2012-08-01 12:00:00'),
('D','2012-08-01 12:00:00','2012-08-01 14:00:00'),
('N','2012-08-01 16:00:00','2012-08-01 18:00:00')
The output should be like this:
StatusCode start_time end_time
B 2012-08-01 08:00:00.000 2012-08-01 10:00:00.000
W 2012-08-01 10:00:00.000 2012-08-01 12:00:00.000
D 2012-08-01 12:00:00.000 2012-08-01 14:00:00.000
B 2012-08-01 14:00:00.000 2012-08-01 16:00:00.000
N 2012-08-01 16:00:00.000 2012-08-01 18:00:00.000
B 2012-08-01 18:00:00.000 2012-08-01 20:00:00.000
The beging and end of the day are declared as below.
declare @begingOfDay datetime='2012-08-01 08:00:00.000'
declare @endOfDay datetime='2012-08-01 20:00:00.000'
Basically I want to have missing time range records in the result set between begingOfDay and endOfDay with statusCode B . Please see that in the output there are 3 records added with StatusCode B
Could anybody help with this?
Your sample data (note,
Ts added to strings to enforce unambiguous date conversions):And the query:
Result:
Note, I’ve proceeded on the assumption that there are no overlapping time periods in the original table. The first CTE (
AllDTs) just finds all unique datetime values that are of interest to us.OrderedDTsandPeriodsthan arrange all of these datetime values into successive periods. The final query then takes each of these periods, and attempts to match them back to the original table, if possible. If not, then it’s obviously aBperiod.