You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在MS SQL Server中查找连续日期范围的方案求助

合并重叠日期范围的SQL问题

我在论坛搜索了类似的日期范围Gaps and Islands问题,但没找到符合我场景的解决方案。现有的相关帖子处理的都是无重叠起始日期的情况,和我的数据集不符。

建表与插入数据语句

create table test_0907 (PRODUCT_TIER4_DESC nvarchar(15), PRODUCT_TIER5_DESC nvarchar(15), BEGIN_EFFECTIVE_DT date, END_EFFECTIVE_DT date)

insert into test_0907 values ('Cloud', 'Other', '2018-03-01 00:00:00.000', '2020-12-31 00:00:00.000')
insert into test_0907 values ('Cloud', 'Other', '2019-07-01 00:00:00.000', '2020-12-31 00:00:00.000')
insert into test_0907 values ('Cloud', 'Other', '2020-12-01 00:00:00.000', '2020-12-31 00:00:00.000')
insert into test_0907 values ('Cloud', 'Other', '2021-01-01 00:00:00.000', '2021-06-30 00:00:00.000')
insert into test_0907 values ('Other', 'Other', '2021-09-01 00:00:00.000', '2021-09-30 00:00:00.000')
insert into test_0907 values ('Cloud', 'Other', '2021-09-01 00:00:00.000', '9999-12-31 00:00:00.000')
insert into test_0907 values ('Cloud', 'Other', '2022-02-01 00:00:00.000', '9999-12-31 00:00:00.000')

期望输出

PRODUCT_TIER4_DESCPRODUCT_TIER5_DESCBEGIN_EFFECTIVE_DTEND_EFFECTIVE_DT
CloudOther2018-03-012021-06-30
OtherOther2021-09-012021-09-30
CloudOther2021-09-019999-12-31

我尝试过用LAG和LEAD函数,但没能得到预期结果。请问还有其他分析函数可以用来解决这个问题吗?

编辑说明:此问题与其他相关帖子不同,因为其他帖子中的起始日期不存在重叠,而我的示例中前3行的BEGIN_EFFECTIVE_DT均小于第3行的END_EFFECTIVE_DT,数据集和所需的查询逻辑都不一样。


内容的提问来源于stack exchange,提问作者Arty155

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 07:09:23