选择日期不在列表中的两个日期之间的天数差异

时间:2013-06-04 07:45:56

标签: sql sql-server

我想选择两个日期(startDate和endDate)之间的日期列表,其中日期不会出现在单独的列表中(假期)。

例如我使用过:

select dateadd(day, number, StartDate)
from 
    (select distinct number from master.dbo.spt_values
        where name is null
    ) n
where dateadd(day, number, StartDate) < EndDate

这给了我两个日期之间的日期列表。但是,我想拿出并计算不在假日日期列表中的日子。

谢谢,

Firstcape

1 个答案:

答案 0 :(得分:2)

试试这个 -

查询1:

DECLARE 
      @DateFrom DATETIME
    , @DateTo DATETIME

SELECT 
      @DateFrom = '20130101'
    , @DateTo = '20130131'

DECLARE @holidays TABLE ([Date] DATETIME)
INSERT INTO @holidays ([Date])
VALUES ('20130101')

SELECT [Date]
FROM (
    SELECT [Date] = DATEADD(DAY, sv.number, t.DateFrom)
    FROM (
        SELECT 
              DateFrom = @DateFrom
            , diff = DATEDIFF(DAY, @DateFrom, @DateTo)
    ) t
    JOIN [master].dbo.spt_values sv ON sv.number <= diff
    WHERE sv.[type] = 'p'
) t2
WHERE t2.[Date] NOT IN (SELECT h.[Date] FROM @holidays h)

查询2:

SELECT t2.[Date]
FROM (
    SELECT [Date] = DATEADD(DAY, sv.number, t.DateFrom)
    FROM (
        SELECT 
              DateFrom = @DateFrom
            , diff = DATEDIFF(DAY, @DateFrom, @DateTo)
    ) t
    JOIN [master].dbo.spt_values sv ON sv.number <= diff
    WHERE sv.[type] = 'p'
) t2
LEFT JOIN @holidays h ON h.[Date] = t2.[Date]
WHERE h.[Date] IS NULL

<强>输出:

Date
-----------------------
2013-01-02 00:00:00.000
2013-01-03 00:00:00.000
2013-01-04 00:00:00.000
2013-01-05 00:00:00.000
2013-01-06 00:00:00.000
2013-01-07 00:00:00.000
2013-01-08 00:00:00.000
...