這是一種方法。
DECLARE @startdate DATE = '2010-10-01'
DECLARE @enddate DATE = '2011-01-02';
WITH FullRange AS
(
SELECT @startdate AS [DATE]
UNION ALL
SELECT DATEADD(d,1,[DATE])
FROM FullRange
WHERE [DATE] < @enddate
),
DatesTable AS
(
SELECT CAST('2010-10-01' AS DATE) Datefrom, CAST('2011-01-01' AS DATE) datetill UNION ALL
SELECT CAST('2011-02-01' AS DATE) Datefrom, CAST('2011-05-16' AS DATE) datetill UNION ALL
SELECT CAST('2011-08-08' AS DATE) Datefrom, CAST('2011-09-01' AS DATE) datetill
)
/*Return any dates in the range that are unmatched*/
SELECT FullRange.[DATE]
FROM FullRange
WHERE NOT EXISTS
(SELECT * FROM DatesTable WHERE [DATE] BETWEEN Datefrom AND datetill)
OPTION (MAXRECURSION 0)
時間段條目是否可能重疊?澄清一下,你的第二條記錄是否可以從2010-12-31開始? – InSane 2010-08-24 10:54:08
您使用的是什麼RDBMS? – 2010-08-24 10:54:51
期間條目可能重疊,並且可能存在「漏洞」。 我們使用MS-SQL Server 2008 – 2010-08-24 11:02:55