获取每个小时的时间范围

时间:2012-06-11 19:30:53

标签: sql sql-server sql-server-2008-r2

所以我想要的是生成特定时间范围内的所有小时数。

所以考虑到上午11点到下午2点,我会得到:

 11:00 AM
 12:00 PM
 1:00 PM
 2:00 PM

我试图避免必须存储每个特定小时的商店可能会打开并只存储范围(我需要将小时与其他时间进行比较)

由于

5 个答案:

答案 0 :(得分: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;

答案 1 :(得分:7)

您可以使用递归CTE。这将产生11到14之间的小时:

;with   Hours as
        (
        select  11 as hr
        union all
        select  hr + 1
        from    Hours
        where   hr < 14
        )
select  *
from    Hours

Live example at SQL Fiddle.

答案 2 :(得分:5)

如果你有numbers table(如果你没有,请点击链接创建一个)......

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)

如果这是专门的,您可以创建一个只有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

答案 3 :(得分:4)

我能想到的最简单的方法是只有一个永久表,其中包含所有小时的列表;总共24个条目。

Create table dbo.Hours (Hourly_Time Time NOT NULL)
Insert into dbo.Hours ...

然后,给定时间A&amp; B:

select * from dbo.Hours where Hourly_Time<=A and Hourly_Time>=B

答案 4 :(得分:0)

@Andomar非常感谢,你帮了我,我的代码上面有我的补充。

*----------------------------

create view vw_hoursalot as 
  with Hours as
  (
      select DATEADD(
        dd, 0, DATEDIFF(
              dd, 0, DATEADD (
                    year , -5 , getDate() 
                  )
            )
      ) as dtHr
    union all
      select DATEADD (minute , 30 , dtHr ) 
        from Hours
        where dtHr < DATEADD(
            dd, 0, DATEDIFF(
                  dd, 0, DATEADD (
                        year , +5 , getDate() 
                      )
                )
        )
  )  
  select * from Hours
----------------------------  
select * from vw_hoursalot option (maxrecursion 0)
----------------------------*