合并重叠的日期间隔(改进的解决方案)
合并重叠的日期间隔是数据处理中的常见任务。虽然提供的解决方案很简单,但它可能不是最有效或最全面的。这是解决潜在边缘情况的改进解决方案:
-- Retrieve the overlapping ranges SELECT s1.StartDate, MIN(t1.EndDate) AS EndDate FROM @T s1 INNER JOIN @T t1 ON s1.StartDate <= t1.EndDate AND NOT EXISTS(SELECT * FROM @T t2 WHERE t1.EndDate >= t2.StartDate AND t1.EndDate < t2.EndDate) GROUP BY s1.StartDate -- Exclude subintervals EXCEPT -- Find overlapping intervals with extended end dates SELECT s1.StartDate, MAX(t1.EndDate) AS EndDate FROM @T s1 INNER JOIN @T t1 ON s1.StartDate > t1.StartDate AND s1.StartDate <= t1.EndDate GROUP BY s1.StartDate
此查询考虑了重叠可能超出原始范围的情况。 EXCEPT 子句过滤掉这些扩展范围,从而得到更准确、更完整的合并区间集。
输出:
StartDate | EndDate 2010-01-01 | 2010-06-13 2010-06-15 | 2010-08-16 2010-11-01 | 2010-12-31
以上是如何高效合并重叠的日期间隔?的详细内容。更多信息请关注PHP中文网其他相关文章!