繁体   English   中英

通过先前的记录字段值更新字段

[英]Updating field by previous record field value

我想从同一表中的先前记录日期字段更新日期字段,例如:

ID_1   ID_2                  start_date                   end_date   
  1     33          2017-12-14 10:28:32.203000              null
  1     33          2017-12-13 10:28:29.153000              null    
  1     33          2017-12-12 10:28:25.246000              null    
  1     33          2017-12-11 10:28:21.917000              null    
  2      4          2017-12-10 10:28:18.005000              null    
  2      4          2017-12-09 10:28:14.145000              null    
  2      4          2017-12-08 13:24:26.964834              null

我想通过具有相同ID_1和ID_2的Recod中的前一个start_date值来更新end_date字段。 举个例子 :

   ID_1  ID_2                start_date                   end_date   
    2      4            2017-12-08 13:24:26.964834     2017-12-09 10:28:14.145000

谢谢

在Postgres中,您可以执行以下操作:

update t
    set end_date = tn.next_start_date
    from (select t.*,
                 lead(start_date) over (partition by id_1, id_2 order by start_date) as next_start_date
          from t
         ) tn
    where tn.id_1 = t.id_1 and tn.id_2 = t.id_2 and tn.start_date = t.start_date

暂无
暂无

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

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