Imran Hemani
Imran Hemani

Reputation: 629

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 ?

Upvotes: 1

Views: 303

Answers (2)

Tharunkumar Reddy
Tharunkumar Reddy

Reputation: 2813

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 

Upvotes: 2

Gordon Linoff
Gordon Linoff

Reputation: 1269793

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.

Upvotes: 2

Related Questions