merge dates when dates following previous record with zero or one day gap(合并日期:前一条记录后的日期间隔为零或一天)
本文介绍了合并日期:前一条记录后的日期间隔为零或一天的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在SQL Server中,当开始日期在结束日期之后或开始日期等于结束日期时,我要根据ID将多个记录合并为单个记录,并在该组中获得Max(ID2)
下面是示例输入和输出。还添加了输入表的SQL代码:
create table #T (ID1 INT, ID2 INT, StartDate DATE, EndDate DATE)
insert into #T values
(100, 764286, '2019-05-01', '2019-05-31'),
(100, 764287, '2019-06-01', '2019-06-30'),
(100, 764288, '2019-07-10', '2019-07-31'),
(101, 764289, '2020-02-01', '2020-02-29'),
(101, 764290, '2020-02-29', '2020-03-31'),
(102, 764291, '2021-10-01', '2021-10-31'),
(102, 764292, '2021-11-01', '2021-11-30'),
(102, 764293, '2021-11-30', '2021-12-31'),
(103, 764294, '2022-01-01', '2022-01-31');
这是我尝试过的脚本,但它没有给出我期望的ID 100的结果,它不应该合并与ID 100相关的所有记录
select m.ID1,
NewID2 AS ID2,
m.StartDate,
lead(dateadd(day, -1, StartDate), 1, MaxEndDate) over (partition by ID1 order by StartDate) as EndDate
from (select *,
lag(StartDate) over (partition by ID1 order by StartDate) as S1,
lag(StartDate) over (partition by ID1 order by StartDate) as S2,
max(EndDate) over (partition by ID1) as MaxEndDate,
max(ID2) over (partition by ID1) as NewID2
from #T
) m
where S2 is null or S1 <> S2;
推荐答案
fiddle
select id1, max(id2) as id2, min(startdate) as startdate, max(enddate) as enddate
from
(
select *, sum(addone) over(partition by id1 order by startdate,enddate,id2 rows unbounded preceding) as grp
from
(
select *,
case when startdate <= dateadd(day, 1, max(enddate) over(partition by id1 order by startdate,enddate,id2 rows between unbounded preceding and 1 preceding))
then 0
else 1
end as addone
from #T
) as r
) as g
group by id1, grp
order by id1, startdate ;
这篇关于合并日期:前一条记录后的日期间隔为零或一天的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:合并日期:前一条记录后的日期间隔为零或一天
基础教程推荐
猜你喜欢
- 使用 VBS 和注册表来确定安装了哪个版本和 32 位 2021-01-01
- 带有WHERE子句的LAG()函数 2022-01-01
- 如何在 CakePHP 3 中实现 INSERT ON DUPLICATE KEY UPDATE aka upsert? 2021-01-01
- MySQL 5.7参照时间戳生成日期列 2022-01-01
- MySQL根据从其他列分组的值,对两列之间的值进行求和 2022-01-01
- while 在触发器内循环以遍历 sql 中表的所有列 2022-01-01
- CHECKSUM 和 CHECKSUM_AGG:算法是什么? 2021-01-01
- 带更新的 sqlite CTE 2022-01-01
- ORA-01830:日期格式图片在转换整个输入字符串之前结束/选择日期查询的总和 2021-01-01
- 从字符串 TSQL 中获取数字 2021-01-01
