填写日期之间的时间,可以不用递归cte来完成

时间:2019-05-11 06:46:25

标签: sql sql-server tsql

下面的代码为我提供了正确的结果,但是在sql中可以在没有递归cte的情况下完成? 也许是十字架。

declare @t table
(locationID int,
 StartTime datetime,
 EndTime datetime
)

 insert @t
 values (1,'1900-01-01 08:00','1900-01-01 19:30')
 ;
 insert @t
 values (2,'1900-01-01 10:00','1900-01-01 15:00')
 ;
 insert @t
 values (3,'1900-01-01 09:30','1900-01-01 21:00')
 ;
with cte_t
as
(
  select locationID, StartTime, EndTime, StartTime as [Time]
  from @t
 union all
  select locationID, StartTime, EndTime, dateadd(mi,30,[Time]) as [Time]
  from cte_t
  where [Time] < [EndTime]
)

select * from cte_t order by locationID

1 个答案:

答案 0 :(得分:0)

with sample_data_table
as
(
    select locationID,cast(StartTime as datetime) as StartTime,cast(EndTime as datetime) EndTime
    from (values (1,'1900-01-01 08:00','1900-01-01 19:30')
                ,(2,'1900-01-01 10:00','1900-01-01 15:00')
                ,(3,'1900-01-01 09:30','1900-01-01 21:00')
    ) t(locationID,StartTime,EndTime)
)

, cte_times AS
(
 SELECT  TOP ((DATEDIFF(HOUR , cast('19000101' as datetime), cast('19000102' as datetime))*2))
 ROW_NUMBER() OVER (ORDER BY number) AS rownum,
 DATEADD(minute, (ROW_NUMBER() OVER (ORDER BY number) -1)*30, cast('19000101' as datetime)) AS dt
 FROM [master].dbo.spt_values
 WHERE [type] = N'P' 
)

 select a.*, b.*
 from sample_data_table as a
 inner join cte_times as b on a.StartTime <= b.dt and a.EndTime >= b.dt
 order by a.locationID,b.dt