我在db Time Parameter(00:15),StartTime(09:00),EndTime(15:00)中有3列
现在我希望在09:00到15:00之间以00:15分的间隔显示所有时间
我应该写什么查询,以便返回如下所示的值:
09:00 - 09:15
09:15 - 09:30
09:30 - 09:45
-
-
-
-
14:45 - 15:00
答案 0 :(得分:6)
使用CTE并假设hour part of @time is zero
:
declare @time time(0) = '00:15',
@start time(0) = '12:00',
@end time(0) = '15:00'
;with cte as (
select @start sTime, dateadd(minute, datepart(minute,@time), @start) eTime
union all
select eTime, dateadd(minute, datepart(minute,@time), eTime)
from cte
where dateadd(minute, datepart(minute,@time), eTime) <= @end
)
select left(sTime,5) + ' - ' + left(eTime, 5) results
from cte
--results
12:00 - 12:15
12:15 - 12:30
12:30 - 12:45
12:45 - 13:00
13:00 - 13:15
13:15 - 13:30
13:30 - 13:45
13:45 - 14:00
14:00 - 14:15
14:15 - 14:30
14:30 - 14:45
14:45 - 15:00
答案 1 :(得分:1)
使用公用表表达式(CTE)生成一个包含所需时间的表。
Declare @strtDt smallDatetime = '15 May 2013 09:00';
Declare @endDt smallDateTime = '15 May 2013 15:00';
With DateTimes(dt) As
(Select @strtDt
Union All
Select DateAdd(minute, 15, dt)
From DateTimes
Where dt < @endDt)
Select dt from DateTimes
option (maxrecursion 10000)