Adding sequence number to existing rows based on ID and Date in PLSQL Oracle [closed]

dba.stackexchange https://dba.stackexchange.com/questions/219322

  •  12-01-2021
  •  | 
  •  

Вопрос

I want to add a sequence number (SEQNO) based on their REFNO and STARTD.

Old Table

New Table

Это было полезно?

Решение

begin
 For r in (Select t.*,
  row_number() over (partition by refno order by startd) seqno
  From my_table t
  Order by refno, startd) loop
   Update my_table
     set seqno = r.seqno
     where refno = r.refno
       and startd = r.startd;
 End loop;
 Commit;
End;

See http://sqlfiddle.com/#!4/484b3/5 for example of row_number. This pl/sql anonymous block can only handle a limited number of records.

Другие советы

You can use MERGE:

merge 
  into tableX t
  using 
  ( select t.*, 
           row_number() over (partition by refno order by startd) as rn
    from tableX t
  ) r
  on ( t.refno = r.refno and t.startd = r.startd )
when matched
  then update
  set
   seqno = r.rn ;

Test in dbfiddle.uk.

(I assume that the PK is (refno, startd)

Лицензировано под: CC-BY-SA с атрибуция
Не связан с dba.stackexchange
scroll top