2015-12-02 61 views
1

更新行我有以下方式的數據:甲骨文:基於列的值

ORDER_NO FULFILL_ID SOURCE_LOC ITEM 
    100     11001  0021 
    100     11001  0031 
    100     12001  0014 
    100     13001  0053 

每當source_loc是一樣的,應該給予同樣的fulfill_id。 相對應的ID從1遞增1開始。所以該數據應更新內容

ORDER_NO FULFILL_ID SOURCE_LOC ITEM 
    100   1   11001  0021 
    100   1   11001  0031 
    100   2   12001  0014 
    100   3   13001  0053 

如何更新列?

+0

你想存儲在表FULFILL_ID價值?這有點危險,這就是當一行被插入/更新/刪除時,數據不一致的原因。改爲創建一個視圖。 (或使用觸發器。) – jarlh

回答

3

這可以用一個單一的MERGE語句來完成:

merge into orders o 
using 
(
    select order_no, 
     dense_rank() over (order by source_loc) as rn, 
     source_loc, 
     item 
    from orders 
) t on (o.order_no = t.order_no and o.item = t.item and o.source_loc = t.source_loc) 
when matched then update 
    set fullfill_id = rn; 

的問題是:爲什麼你需要保存這些信息,如果這可以很容易地在運行時計算。

您可以創建這樣一個觀點:

create or replace view orders_2 
as 
select order_no, 
     dense_rank() over (order by source_loc) as fullfill_id, 
     source_loc, 
     item 
from orders 
+0

正在提供的數據將此列設置爲空。 所以這需要手動填充。 –

+0

@ImranHemani。我想說的是,你根本不需要_store_。 –

+0

是的,我同意你的意見。但這就是客戶的要求。 –

0

我不知道它的問題,但是,如果新的記錄都在用相同的source_loc領域,要確保它們保存和繼承先前分配值fulfill_id那麼這樣的事情可能會奏效,以確保以前的ID被繼承和新的ID分配:

update mytable t1 
set t1.fulfill_id = (
    with already as (
    select distinct source_loc, fulfill_id 
    from mytable 
    where fulfill_id is not null 
), 
    final_id as (
    select distinct 
     m.source_loc, 
     coalesce (a.fulfill_id, dense_rank() over (order by m.source_loc)) as fulfill_id  
    from 
     mytable m, 
     already a 
    where 
     m.source_loc = a.source_loc (+) 
) 
    select 
    f.fulfill_id 
    from final_id f 
    where 
    f.source_loc = t1.source_loc 
) 
where t1.fulfill_id is null; 

以這種方式,一旦fulfill_id分配給source_loc,它的保留。

ORDER_NO FULFILL_ID SOURCE_LOC ITEM 
    100   1   11001  0021 
    100   1   11001  0031 
    100   2   12001  0014 
    100   3   13001  0053 
    100      12001  0014 
    100      10001  0014 

最終會是這樣:即開始這樣的數據

ORDER_NO FULFILL_ID SOURCE_LOC ITEM 
    100   1   11001  0021 
    100   1   11001  0031 
    100   2   12001  0014 
    100   3   13001  0053 
    100   2   12001  0014 
    100   4   10001  0014