SQL Server - 从表中获取两个日期之间的日期列表

时间:2016-03-22 06:19:46

标签: sql sql-server

我有以下格式的表格

TblHoliday    

StrDate     EndDate     Rmrks
-----------------------------------------
2016-03-26  2016-03-26  BankHoliday
2016-04-07  2016-04-09  YearlyHolidays

我需要以下列格式获取假期列表

Expected Result

Date1
-------------
2016-03-26
2016-04-07
2016-04-08
2016-04-09

我正在使用以下查询,但我没有在此查询中获得2016-04-09。

ActualResult

Date1
-------------
2016-03-26
2016-04-07
2016-04-08

当前查询

;with cte as
(
select T1.StrDate as [Date1] from TblHoliday T1
union all
select DATEADD(DD,1,T1.StrDate) as [Date1] from TblHoliday T1 where  DATEADD(DD,1,T1.StrDate)<=T1.EndDate
)

select Date1 from cte

我需要使用此查询的假期日期列表,其中假日在日期范围内定义。

感谢。

2 个答案:

答案 0 :(得分:0)

以下是使用Tally Table.

的解决方案
WITH E1(N) AS(
    SELECT 1 FROM (VALUES (1),(1),(1),(1),(1),(1),(1),(1),(1),(1))t(N)
),
E2(N) AS(SELECT 1 FROM E1 a CROSS JOIN E1 b),
E4(N) AS(SELECT 1 FROM E2 a CROSS JOIN E2 b),
CteTally(N) AS(
    SELECT TOP(SELECT MAX(DATEDIFF(DAY, StrDate, EndDate)) + 1 FROM TblHoliday)
        ROW_NUMBER() OVER(ORDER BY (SELECT NULL))
    FROM E4
)
SELECT
    dt = DATEADD(DAY, t.N- 1, h.StrDate)
FROM TblHoliday h
INNER JOIN CteTally t
    ON DATEADD(DAY, t.N- 1, h.StrDate) <= h.EndDate

答案 1 :(得分:0)

declare @TblHoliday table (StrDate date, EndDate date)
insert @TblHoliday values ('2016-03-26', '2016-03-26'), ('2016-04-07', '2016-04-09')

-- Build a tally table using date range from the data
;with cte as
(
    select min(StrDate) as value, max(EndDate) as maxvalue from @TblHoliday
    union all select dateadd(day, 1, value), maxvalue from cte where dateadd(day, 1, value) <= maxvalue
)
select value from cte 
-- filter out the dates
where exists(select * from @TblHoliday where value between StrDate and EndDate)
option(maxrecursion 0)