, @gbn . .
- , timedata, ,
WITH normalized AS
(
SELECT *
FROM timedata
WHERE datepart(day,start_time) = datepart(day,endtime)
UNION ALL
SELECT id, rate, start_time, dateadd(second,dateadd(day,datediff(day,0,end_time),0),-1) as end_time
FROM timedata
WHERE not (datepart(day,start_time) = datepart(day,endtime))
UNION ALL
SELECT id, rate,dateadd(day,datediff(day,0,end_time),0) as start_time, end_time
FROM timedata
WHERE not (datepart(day,start_time) = datepart(day,endtime))
)
SELECT *
FROM normalized
WHERE datepart(hour,start_time) < @inhour
AND datepart(hour,end_time) > @inhour
CTE . , : SQL-
, :
,
,
- Selects a start time and one second until the next day as the end time for this entire range.
and
- Select the date 12 days at the endpoint as start time and end_time.
Finally, you make the selection using the hour indicator in this normalized table.
If your ranges go beyond more than one day, you will need to use a recursive CTE to get the same normalized table.
Hogan source
share