In PL/SQL, how do you update a row based on the next row?

后端 未结 5 1117
轮回少年
轮回少年 2021-01-18 10:20

I\'m using Oracle PL/SQL.

I have a timestamped table T, and I want to set a row\'s value for column A to be the same as that of the previous row, if they\'re sorted

5条回答
  •  遥遥无期
    2021-01-18 10:45

    Try using a merge statement. Not sure it quite does what you want but it should work. Unfortunately the insert clause is necessary) but shouldn't ever be called.

    merge into t a
    using (
      select 
        A, 
        B, 
        timestamp, 
        lag(A) over (order by id, timestamp) as prior_A,
        lag(timestamp) over (order by B, timestamp) as prior_timestamp
      from t) b
    on  (a.B = b.B)
    when matched then 
      update set a.a = case when b.timestamp-b.prior_timestamp <= 45 
        then b.prior_A else b.A end
    when not matched then insert (B) values (null)
    

提交回复
热议问题