【问题标题】:merge dates when dates following previous record with zero or one day gap当日期跟在前一条记录之后的日期为零或一天的间隔时合并日期
【发布时间】:2022-01-06 08:55:11
【问题描述】:

当开始日期在结束日期之后或开始日期等于 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;

【问题讨论】:

  • Edit 问题并展示您已经尝试过的内容。解释失败的原因/位置。具体(错误消息、意外结果等)。
  • 更新了@stickybit
  • 根据问题指南,请不要发布代码、数据、错误消息等的图像 - 将文本复制或键入问题中。请保留将图像用于图表或演示渲染错误,无法通过文本准确描述的事情。

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


【解决方案1】:

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 ;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-30
    • 2012-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-18
    相关资源
    最近更新 更多