简体   繁体   English

更新SCD2表中的记录

[英]Update a Record in a SCD2 Table

I have a table in which the entries are historized with SCD 2 the table look like this: 我有一个表,其中的条目用SCD 2进行了历史记录,该表如下所示:

PK              ValidFrom   ValidTo
635582110901    04.01.2016  21.01.2016
635582110901    22.01.2016  26.01.2016
635582110901    27.01.2016  14.02.2016
635582110901    15.02.2016  10.11.2016
635582110901    11.11.2016  23.01.2017 <--
635582110901    16.11.2016  12.12.2016
635582110901    13.12.2016  18.01.2017
635582110901    19.01.2017  22.01.2017
635582110901    23.01.2017  23.01.2017
635582110901    24.01.2017  21.02.2017
635582110901    22.02.2017  31.12.9999

The record marked with the arrow is incorect This record is to be corrected with an update. 用箭头标记的记录不正确。该记录将通过更新进行更正。 so after the Update the Record look like this: (the ValidTo = ValidFrom -1 from the next Record) 因此,在更新记录后,如下所示:(下一条记录的ValidTo = ValidFrom -1)

635582110901    15.02.2016  10.11.2016
635582110901    11.11.2016  15.11.2016 
635582110901    16.11.2016  12.12.2016

If there are several incorect records these must also be corrected with an update ValidFrom is correct and does not have to be adjusted 如果存在多个不正确的记录,则还必须通过更新来更正这些记录。ValidFrom是正确的,不必进行调整

Can someone please help me? 有人可以帮帮我吗? Thx 谢谢

Because your data is "almost in order", you can use lead() for this purpose: 因为您的数据“几乎是有序的”,所以您可以为此使用lead()

with toupdate as (
      select t.*,
             lead(validfrom) over (partition by pk order by validfrom) as next_validfrom
      from t
     )
update toupdate
    set validto = dateadd(day, -1, next_validfrom)
    where validto <> dateadd(day, -1, next_validfrom);

I have to emphasize that this will tile all the data for a primary key. 我必须强调,这将为主键平铺所有数据。 If gaps are allowed, then use this version: 如果允许空白,请使用以下版本:

update toupdate
    set validto = dateadd(day, -1, next_validfrom)
    where validto > dateadd(day, -1, next_validfrom);

This does the update only when there is an overlap. 仅在有重叠时才进行更新。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM