sql - 合并前一个记录之后的日期有零天或一天间隔的日期

标签 sql sql-server database window-functions gaps-and-islands

当开始日期跟随结束日期或开始日期等于 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');

Sample input & output

这是我尝试过的脚本,但它没有给出我期望的 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 ;

关于sql - 合并前一个记录之后的日期有零天或一天间隔的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70604632/

相关文章:

php - 如何在 SELECT 语句的 WHERE 子句中传递 php 变量?

mysql - 学习存储过程,简单查询(IN ... OUT ...)

mysql - 查询获取每个客户每周的平均支出

sql - 修改现有触发器的程序

python - 使用 Python 连接到 PostgreSQL

mysql - 获取大表中最后修改记录的最有效查询

javascript - 使用 angularjs 和 sql server 数据库自动完成功能

sql-server - Excel VBA 到 SQL Server(无需 SSIS)

c# - 是否可以在存储过程的输出变量中使用 MERGE 语句的 $action?

mysql - SQL查询条件,用于根据条件获取用户的答案