如何在服务器上写CTE,以获取 End_Date
,用于分行,分机由人与人分行; 类型,从个人类型变化开始。 <代码>End_Date在个人分治内被定义为下一个类型分级的
I previously asked a similar question, which gained an answer, but I had neglected to show the case where the Type might no only change multiple times within a Person, but might also repeat the same Type again. This scenario should also create a new partition as shown in the data below.
For the following source data, records should be sorted by dt_eff
for the person.
资料来源:数据。
Person Type dt_eff
123 ABC 2018-10-23
123 DEF 2018-12-19
124 ABC 2020-01-01
124 ABC 2020-02-15
124 ABC 2020-05-14
124 DEF 2020-10-13 < Note change of Type to DEF
124 ABC 2021-01-15 < Note change of Type back to ABC
预期产出
Person Type Start_Date End_Date Partition
123 ABC 2018-10-23 2018-12-19 123:1 < Start_Date from 123:DEF
123 DEF 2018-12-19 NULL 123:2
124 ABC 2020-01-01 2020-10-13 124:1
124 ABC 2020-02-15 2020-10-13 124:1
124 ABC 2020-05-14 2020-10-13 124:1 < Start_Date from 124:DEF
124 DEF 2020-10-13 2021-01-15 124:2< Start_Date from next 124:ABC
124 ABC 2021-01-15 NULL 124:3
注<代码> 部分编码>栏并非所需产出,只是为澄清而添加。