Reputation: 639
I want to select a list of dates between two dates (startDate and endDate), where the date does not appear in a seperate list (holidays).
For example I have used:
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
Which gives me a list of dates between the two dates. However I want to take out and count the days where not in a list of holidays dates.
Thanks,
Firstcape
Upvotes: 3
Views: 955
Reputation: 122022
Try this one -
Query 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)
Query 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
Output:
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
...
Upvotes: 2