获取SQL Server中日期范围内的所有日期

时间:2012-02-04 10:50:23

标签: sql sql-server-2005 tsql datetime date-range

我从一个被问到的StackOverflow问题中得到了这个例子,但根据我的需要,我无法让它工作。

WITH DateTable
AS
(
    SELECT CAST('20110101' as Date) AS [DATE]
    UNION ALL
    SELECT DATEADD(dd, 1, [DATE]) FROM DateTable 
    WHERE DATEADD(dd, 1, [DATE]) < cast('20110131' as Date)
)
SELECT dt.[DATE] FROM [DateTable] dt

输入 -

ID |   FromDate  | ToDate
=============================
1  |  2011-11-10 | 2011-11-12
2  |  2011-12-12 | 2011-12-14

输出 -

SN |   Dates     | 
==================
1  |  2011-11-10 | 
2  |  2011-11-11 | 
3  |  2011-11-12 | 
4  |  2011-12-12 | 
5  |  2011-12-13 | 
6  |  2011-12-14 |

请参阅此代码适用于静态日期。但在我的情况下,我有一个包含三列Id, FromDate, ToDate的表。现在我想将每行中的每个范围转换为各个日期。

如果范围来自表格,我无法得到上面的例子,显然这个查询必须为范围表中的每一行运行,这是另一个令人困惑的挑战。

请帮忙。

3 个答案:

答案 0 :(得分:4)

create table Dates (Id int, FromDate date, ToDate date)
insert into Dates values (1, '2011-11-10', '2011-11-12')
insert into Dates values (2, '2011-12-12', '2011-12-14')

with DateTable as
(
    select FromDate as Dt, ToDate
    from Dates
    union all
    select DATEADD(D, 1, Dt), ToDate
    from DateTable
    where DATEADD(D, 1, Dt) <= ToDate
)
select ROW_NUMBER() over (order by Dt) as SN, Dt as Dates
from DateTable
order by Dt

答案 1 :(得分:4)

在数字表的帮助下。

declare @T table
(
  ID int identity primary key,
  FromDate date,
  ToDate date
)

insert into @T values
('2011-11-10', '2011-11-12'),
('2011-12-12', '2011-12-14')

select row_number() over(order by D.Dates) as SN,
       D.Dates
from @T as T
  inner join master..spt_values as N
    on N.number between 0 and datediff(day, T.FromDate, T.ToDate)
    cross apply (select dateadd(day, N.number, T.FromDate)) as D(Dates)
where N.type ='P'

试试SE Data

答案 2 :(得分:1)

这个怎么样?

--DROP TABLE #Test
CREATE TABLE #Test(ID int, FromDate datetime, ToDate datetime)
INSERT INTO  #Test VALUES (1, '2011-11-10', '2011-11-12')
INSERT INTO  #Test VALUES (2, '2011-12-12', '2011-12-14')

;
WITH DateTable
AS
(
    SELECT  ID, FromDate, ToDate, 0 AS Seed FROM #Test
    UNION   ALL
    SELECT  ID, DATEADD(dd, 1, FromDate), ToDate, Seed + 1
    FROM    DateTable
    WHERE   DATEADD(dd, 1, FromDate) <= ToDate
)
SELECT  --*
        ROW_NUMBER() OVER (ORDER BY ID, Seed) SN, FromDate AS Dates
FROM    DateTable