在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_DESC | PRODUCT_TIER5_DESC | BEGIN_EFFECTIVE_DT | END_EFFECTIVE_DT |
|---|---|---|---|
| Cloud | Other | 2018-03-01 | 2021-06-30 |
| Other | Other | 2021-09-01 | 2021-09-30 |
| Cloud | Other | 2021-09-01 | 9999-12-31 |
我尝试过用LAG和LEAD函数,但没能得到预期结果。请问还有其他分析函数可以用来解决这个问题吗?
编辑说明:此问题与其他相关帖子不同,因为其他帖子中的起始日期不存在重叠,而我的示例中前3行的BEGIN_EFFECTIVE_DT均小于第3行的END_EFFECTIVE_DT,数据集和所需的查询逻辑都不一样。
内容的提问来源于stack exchange,提问作者Arty155
相关产品推荐
相关产品推荐

