在一段日期范围内获取日期

17

我需要使用SQL Server 2005获取日期范围内的所有日期。


你想生成日期还是只是搜索现有字段? - Unsliced
3
哈里什,请将以下其中一个答复标记为答案。他们花时间来帮助你。 - FMFF
7个回答

56

给你:

DECLARE @DateFrom smalldatetime, @DateTo smalldatetime;
SET @DateFrom='20000101';
SET @DateTo='20081231';
-------------------------------
WITH T(date)
AS
( 
SELECT @DateFrom 
UNION ALL
SELECT DateAdd(day,1,T.date) FROM T WHERE T.date < @DateTo
)
SELECT date FROM T OPTION (MAXRECURSION 32767);

我喜欢那个解决方案。在时间轴上使用类似的方法,这样即使数据库中没有与该时间段匹配的记录,图表仍能保持一致的间隔。 - Kevin Fairchild
1
好的。 这适用于生成任何序列:只需将 DateAdd(day,1,T.date) 替换为其他 this_item=F(previous_item) 公式。 - Incidently
使用CTE的解决方案非常酷。我以前从没见过这样做过。 - jons911
这太棒了。我需要一个能够给我两个日期之间所有星期一的东西。所以我使用了这个,再加上一个使用datepart的额外过滤器,嘭……正是我所需要的。+1。 - RThomas

8
如果您有一个包含日期的表格,并且只想选择两个日期之间的日期,则可以使用以下方法:
select * from yourTable where yourDate between date1 and date2

如果你想从零开始生成日期,可以使用循环或者将日期填充到临时表中,然后从表中选择。


5
DECLARE @Date1 DATE='2016-12-21', @Date2 DATE='2016-12-25'
SELECT DATEADD(DAY,number,@Date1) [Date] FROM master..spt_values WHERE type = 'P' AND DATEADD(DAY,number,@Date1) <= @Date2

这仅适用于较小的日期范围。小于2048天。 - Greg Z.

1

这是Oracle版本的日期生成:

SELECT TO_DATE ('01-OCT-2008') + ROWNUM - 1 g_date
  FROM all_objects
 WHERE ROWNUM <= 15

可以使用任何拥有足够行数的表格来替代 all_objects。


0
稍微复杂但也许更灵活的做法是利用包含一系列顺序数字的表格。这允许有多个具有不同间隔的日期范围。
/* holds a sequential set of number ie 0 to max */
/* where max is the total number of rows expected */
declare @Numbers table ( Number int  )

declare @max int 
declare @cnt int

set @cnt = 0
/* this value could be limited if you knew the total rows expected */
set @max = 999 

/* we are building the NUMBERS table on the fly */
/* but this could be a proper table in the database */
/* created at the point of first deployment */
while (@cnt <= @max)
begin
      insert into @Numbers select @cnt
      set @cnt = @cnt + 1
end

/* EXAMPLE of creating dates with different intervals */

declare @DateRanges table ( 
   StartDateTime datetime, EndDateTime datetime, Interval int )

/* example set of date ranges */
insert into @DateRanges
select '01 Jan 2009', '10 Jan 2009', 1 /* 1 day interval */
union select '01 Feb 2009', '10 Feb 2009', 2 /* 2 day interval */

/* heres the important bit generate the dates */
select
      StartDateTime
from
(
      select
            d.StartDateTime as RangeStart,
            d.EndDateTime as RangeEnd,
            dateadd(DAY, d.Interval * n.Number, d.StartDateTime) as StartDateTime
      from 
            @DateRanges d, @Numbers n
) as dates
where
      StartDateTime between RangeStart and RangeEnd
order by StartDateTime

实际上,我使用这个变体将日期拆分为时间段(具有不同的间隔,但通常为5分钟)。我的@numbers表最多包含288个数字,因为这是24小时内可以有的5分钟时间段的总数。

/* EXAMPLE of creating times with different intervals */

delete from @DateRanges 

/* example set of date ranges */
insert into @DateRanges
select '01 Jan 2009 09:00:00', '01 Jan 2009 12:00:00', 30 /* 30 minutes interval */
union select '02 Feb 2009 09:00:00', '02 Feb 2009 10:00:00', 5 /* 5 minutes interval */

/* heres the import bit generate the times */
select
      StartDateTime,
      EndDateTime
from
(
      select
            d.StartDateTime as RangeStart,
            d.EndDateTime as RangeEnd,
            dateadd(MINUTE, d.Interval * n.Number, d.StartDateTime) as StartDateTime,
            dateadd(MINUTE, d.Interval * (n.Number + 1) , StartDateTime) as EndDateTime
      from 
            @DateRanges d, @Numbers n
) as dates
where
      StartDateTime >= RangeStart and EndDateTime <= RangeEnd
order by StartDateTime

-2

要生成一系列日期,您可以编写一个表值函数。这是一个为数据仓库创建日期维度的函数 - 您可以通过删除特殊字符来轻松地进行适应。

编辑:这是没有日期维度层次结构的版本。

if object_id ('ods.uf_DateHierarchy') is not null
    drop function ods.uf_DateHierarchy
go

create function ods.uf_DateHierarchy (
       @DateFrom datetime
      ,@DateTo   datetime
) returns @DateHierarchy table (
        DateKey           datetime
) as begin
    declare @today           datetime  
    set @today = @Datefrom

    while @today <= @DateTo begin
        insert @DateHierarchy (DateKey) values (@today)
        set @today = dateadd (dd, 1, @today)
    end

    return
end

go

-2
如果您想要获取数据库中两个日期之间的所有日期(即客户在 2008 年 Q3 放置订单的日期),您可以编写以下代码:
select distinct(orderPlacedDate) 
from orders 
where orderPlacedDate between '2008-07-01' and 2008-09-30' 
order by orderPlacedDate

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接