【问题标题】:Creating start and end dates创建开始日期和结束日期
【发布时间】:2019-07-02 17:33:16
【问题描述】:

我有下表

 Createdt    Updatedt    id
 1/1/2019    3/1/2019    1
 1/1/2019    5/1/2019    1
 1/1/2019    7/1/2019    1

预期结果:

Createdt    Start_dt_cycle    End_dt_cycle  id
1/1/2019    1/1/2019          2/28/2019     1 
1/1/2019    3/1/2019          4/30/2019     1
1/1/2019    5/1/2019          06/30/2019    1
1/1/2019    7/1/2019          12/31/9999    1

我的结果:

Createdt    Start_dt_cycle    End_dt_cycle  id
1/1/2019    3/1/2019          4/30/2019     1
1/1/2019    5/1/2019          06/30/2019    1
1/1/2019    7/1/2019          12/31/9999    1

我使用LEAD 函数来捕获所需的end_dt。我正在使用 updatedt 创建循环,但我真的希望循环从 createdt 开始,而不是第一次更新。

【问题讨论】:

  • 也许我创建了一个 cte 并合并了所有不同的日期?

标签: sql oracle lag lead


【解决方案1】:

你似乎想要union alllead()

select id, start_dt_cycle,
       lead(start_dt_cycle, 1, date '9999-12-31') over (partition by id order by start_dt_cycle) as end_dt_cycle
from ((select min(createddt) as start_dt_cycle, id
       from t
       group by id
      ) union all
      (select updatedt, id
       from t
      )
     ) t

【讨论】: