看下图,它代表了一些重叠的时间段
X----| |--------| |------X
|-------X X------------X
|----| X----|
任何连续时间段的开始或结束,标有X
不属于任何其他时间段。如果我们确定这些时间,我们可以取得一些进展。
此查询标识边界。
SELECT boundary FROM
(
-- find all the lower bounds
SELECT d1.StartDate AS boundary, 'lower' as type
FROM dates d1
LEFT JOIN dates d2 ON (
d1.StartDate > d2.StartDate
AND
d1.StartDate < d2.EndDate
)
WHERE d2.RowId IS NULL
GROUP BY d1.StartDate
UNION
-- find all the upper bounds
SELECT d1.EndDate AS boundary, 'upper' as type
FROM dates d1
LEFT JOIN dates d2 ON (
d1.EndDate > d2.StartDate
AND
d1.EndDate < d2.EndDate
)
WHERE d2.RowId IS NULL
GROUP BY d1.StartDate
) as boundaries
ORDER BY boundary ASC
对您的数据进行此查询的结果是
boundry | type
------------------
2011-01-01 | lower
2011-02-20 | upper
2011-03-01 | lower
2011-04-01 | upper
您所追求的日期范围在上面显示的连续下限和上限之间。通过一些后期处理,可以很容易地找到这些。