按先前记录字段值更新字段

时间:2017-12-14 14:36:43

标签: sql database postgresql

我想更新同一个表中上一个记录日期字段的日期字段,例如:

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

由于

1 个答案:

答案 0 :(得分:1)

在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
相关问题