简体   繁体   中英

Oracle SQL Update by rownum

I have the data in the following format:

ORD_NO  ITEM  FULFILL_ID
SA1     1000     1 
SA1     2000     2
SA2     2000     1
SA2     3000     2
SA2     9000     3

I want to fill in the values for the column FULFILL_ID, which should start with 1 and increase till the number of rows for one particular ORD NO, as I have filled above.

How to do it ?

This is what ROW_NUMBER() does:

select ord_no, item,
       row_number() over (partition by ord_no order by item) as fulfill_id
from table t;

This returns the value as a query. A slightly different query is needed for an update.

EDIT:

The update can be done like this:

update table t
    set fulfill_id = (select count(*)
                      from table t2
                      where t2.ord_no = t.order_no and
                            t2.item <= t.item
                     );

This version assumes that item is different for the same values of ord_no .

you can use merge statement for this

merge into table1 t3 using
(
select ord_no, item,
       row_number() over (partition by ord_no order by item) as fulfill_id
from table1 
) s
on 
(t3.ORD_NO=s.ORD_NO and t3.ITEM=s.ITEM)
when matched then
update set t3.FULFILL_ID=s.fulfill_id 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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