Lim*_*mey 5 sql sql-server sql-server-2008-r2
所以我想要的是生成特定时间范围内的所有小时.
所以考虑到上午11点到下午2点,我会得到:
11:00 AM
12:00 PM
1:00 PM
2:00 PM
Run Code Online (Sandbox Code Playgroud)
我试图避免必须存储商店可能打开的每个特定小时,只是存储范围(我需要比较其他时间的小时)
谢谢
Aar*_*and 11
无需循环,递归CTE或数字表.
DECLARE
@start TIME(0) = '11:00 AM',
@end TIME(0) = '2:00 PM';
WITH x(n) AS
(
SELECT TOP (DATEDIFF(HOUR, @start, @end) + 1)
rn = ROW_NUMBER() OVER (ORDER BY [object_id])
FROM sys.all_columns ORDER BY [object_id]
)
SELECT t = DATEADD(HOUR, n-1, @start) FROM x ORDER BY t;
Run Code Online (Sandbox Code Playgroud)
您可以使用递归CTE.这将产生11到14之间的小时:
;with Hours as
(
select 11 as hr
union all
select hr + 1
from Hours
where hr < 14
)
select *
from Hours
Run Code Online (Sandbox Code Playgroud)
如果你有一个数字表(如果你没有,点击链接创建一个)...
create table test(
startTime time
, endTime time
)
insert into test
select '11:00', '14:00'
select
dateadd(hh, n.n, t.startTime) as times
from test t
inner join Numbers n
-- assuming your numbers start at 1 rather than 0
on n.n-1 <= datediff(hh, t.startTime, t.endTime)
Run Code Online (Sandbox Code Playgroud)
如果这是专门的,您可以创建一个只有24个值的小时表.
create table HoursInADay(
[hours] time not null
, constraint PK_HoursInADay primary key ([hours])
)
-- insert
insert into HoursInADay select '1:00'
insert into HoursInADay select '2:00'
insert into HoursInADay select '3:00'
insert into HoursInADay select '4:00'
insert into HoursInADay select '5:00'
insert into HoursInADay select '6:00'
insert into HoursInADay select '7:00'
...
select
h.[hours]
from test t
inner join HoursInADay h
on h.[hours] between t.startTime and t.endTime
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13411 次 |
| 最近记录: |