SQL 根据日期范围加入

SQL join against date ranges

我需要找出日期之间的差异。 table

中的示例数据
CREATE TABLE #TEMP
(

StartDate DATE,
EndDate DATE
)

INSERT INTO #temp
VALUES
('12-01-2021','12-02-2021'),
('12-02-2021','12-03-2021'),
('12-03-2021','12-04-2021'),
('12-13-2021','12-14-2021'),
('12-14-2021','12-15-2021'),
('12-28-2021','12-29-2021')

需要输出:

StartDate EndDate
12-01-2021 12-04-2021
12-13-2021  12-15-2021
12-28-2021  12-29-2021

您可以使用 lag 使用 datediff 查找前一行的结束日期为开始日期的行,然后为每一行保留此差异的总计 运行 . 运行 总数相同的行在同一组中,然后对于每个组,您可以分别获取开始日期和结束日期的最大值和最小值以获得所需的输出。

如果您使用 sql 服务器:

with u as 
(select StartDate,
EndDate,
case when
coalesce(datediff(day, lag(EndDate) over(order by StartDate, EndDate), StartDate), 0) = 0 then 0
else 1 end as change
from #TEMP),
v as
(select *, sum(change) over(order by StartDate, EndDate rows unbounded preceding) as g
from u)
select min(StartDate) as StartDate, max(EndDate) as EndDate from v group by g 

Fiddle