2013-10-07 126 views
0

我需要使用順序值(例如001,002,002)引用同一個表上的另一個字段entity_id來更新varchar2字段。我需要它,例如,如果我在兩個不同的行上具有相同的entity_id,那麼順序值應該是相同的。更新表中的一個字段以引用同一個表上的另一個字段Oracle

一個例子輸出:

Entity_id  Seq_field 
1234   001 
1234   001 
4567   002 
4567   002 
3412   003 

我試圖與ROWNUM但它爲每個ENTITY_ID賦予不同的值,當然該值不具有尾隨零。請幫忙。

回答

3
merge into the_table 
using 
(
    select rowid as rid, 
     entity_id, 
     to_char(dense_rank() over (order by entity_id), 'FM00000') as seq 
    from foo 
) t on (the_table.rowid = t.rid) 
when matched 
    then update set seq_field = t.seq; 

如果你想開始每次需要稍微改變聲明entity_id一個新的序列:

merge into foo 
using 
(
    select rowid as rid, 
     entity_id, 
     to_char(row_number() over (partition by entity_id order by null), 'FM00000') as seq 
    from foo 
) t on (foo.rowid = t.rid) 
when matched 
    then update set seq_field = t.seq; 

請注意,我用row_number()代替dense_rank()partition by entity_id每個新重新啓動編號值爲entity_id。如果您有另一列將確定一個entity_id的「訂單」,那麼您可以用該列替換order by null中的nullorder by created_at

+0

這是正確的。如果我想爲每個實體ID更新001,002,那麼我應該怎麼做,以便當實體ID改變時,號碼再次重複001,002,003 ...? – ErrorNotFoundException

+1

@Stanley:看我的編輯 –

+0

謝謝,也工作。非常感謝你 – ErrorNotFoundException

1

你有多少條記錄?下面是我提出的解決方案,但不能很好地處理大量數據。

CREATE TABLE tab (entity_id NUMBER, seq_field VARCHAR2(3)); 

INSERT INTO tab VALUES (1234, NULL); 
INSERT INTO tab VALUES (1234, NULL); 
INSERT INTO tab VALUES (4567, NULL); 
INSERT INTO tab VALUES (4567, NULL); 
INSERT INTO tab VALUES (3412, NULL); 

UPDATE tab t SET seq_field = (
    SELECT LPAD(rnk, 3, '0') 
    FROM (
     SELECT entity_id, seq_field, DENSE_RANK() OVER (ORDER BY entity_id) AS rnk 
     FROM tab 
    ) t2 
    WHERE t2.entity_id = t.entity_id AND rownum = 1 
); 

檢查在SQLFiddle:http://sqlfiddle.com/#!4/3959d/1

考慮加入兩個SQLORACLE標記你的問題,你猜你會得到更多的關注,也許一個更好的解決方案。

相關問題