Создайте табличную функцию и вызовите ее, чтобы создать таблицу дат и часов;
SELECT CONVERT(varchar(10),[Start_Date],101)'Date', DATEPART(HOUR,[Start_Date])'Hour'
FROM generateDateTable('1/1/2019','1/12/2019','hour',1)
WHERE DATEPART(HOUR,[Start_Date]) >= 7
Определение функции;
CREATE function [dbo].[generateDateTable]
(
@start_date datetime
, @end_date datetime
, @datepart varchar(20) = 'day'
, @step int = 1
)
returns @dates table
(
start_date datetime,
end_date datetime
)
as
begin
if( @datepart in ('year', 'yy', 'yyyy', 'quarter', 'qq', 'q', 'month', 'mm', 'm',
'dayofyear', 'dy', 'y', 'day', 'dd', 'd', 'week', 'wk', 'ww') )
begin
set @start_date = cast(floor(cast(@start_date as float)) as datetime)
set @end_date = cast(floor(cast(@end_date as float)) as datetime)
end
declare @new_start datetime
while @start_date <= @end_date
begin
set @new_start = (case
when @datepart in ('year', 'yy', 'yyyy') then dateadd(yy, @step, @start_date)
when @datepart in ('quarter', 'qq', 'q') then dateadd(qq, @step, @start_date)
when @datepart in ('month', 'mm', 'm') then dateadd(mm, @step, @start_date)
when @datepart in ('dayofyear', 'dy', 'y') then dateadd(dy, @step,
@start_date)
when @datepart in ('day', 'dd', 'd') then dateadd(dd, @step, @start_date)
when @datepart in ('week', 'wk', 'ww') then dateadd(ww, @step, @start_date)
when @datepart in ('hour', 'hh') then dateadd(hh, @step, @start_date)
when @datepart in ('minute', 'mi', 'n') then dateadd(n, @step, @start_date)
when @datepart in ('second', 'ss', 's') then dateadd(s, @step, @start_date)
when @datepart in ('millisecond', 'ms') then dateadd(ms, @step, @start_date)
else dateadd(dd, @step, @start_date)
end)
insert
@dates
(
start_date
, end_date
) values (
@start_date
, dateadd(ms, -3, @new_start)
)
set @start_date = @new_start
end
return
end