2015-09-28 84 views
1

我有數據的格式如下:的Oracle SQL更新由ROWNUM

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

我要填寫的列FULFILL_ID值,應該從1開始,並增加至行的一個數特別是ORD NO,正如我在上面填寫的那樣。

怎麼辦?

回答

2

這是ROW_NUMBER()做:

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

這將返回值的查詢。更新需要稍微不同的查詢。

編輯:

更新可以這樣進行:

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

此版本假定item是的ord_no相同的值不同。

+0

項目可同爲訂單。我需要將每一行更新爲不同的數字。 –

+1

我相信當用這種方式從相關的子查詢中更新時,Oracle的性能很糟糕。 – MatBailie

2

可以用MERGE語句,此

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 
+0

項目可能不是唯一的任何特定訂單號碼 如何基於OrderNo下的行數一般更新fulfill_id? –

+0

@imran hemani你可以請發表那種情況? – Buddi

+0

如果100行有一個ord_no,它會給出1到100的數字並更新fulfill_id。我們正在ord_no列上進行分區。 – Buddi