2017-08-02 51 views
-5

我有表contacts如何更新隨機預言另一個表

ID  CONTACT_ID  TYPE_ID 
1   5    1 
2   8    1 
3   9    1       
4   12    2   
5   13    1   
6   17    2       
7   22    2       
8   23    2  
9   25    1  
10   33    2     
11   34    2      
12   48    1  
.   ...    ...  
n   n    2 

如何更新CONTACT_ID隨機的,但不會改變TYPE_ID(其中TYPE_ID = 1個隨機更新這個接觸或其中TYPE_ID = 2->更新隨機這個觸點) 例如

ID  CONTACT_ID  TYPE_ID 
    1   9    1 
    2   13    1 
    3   8    1       
    4   17    2   
    5    5    1   
    6   22    2       
    7   12    2       
    8   33    2  
    9   48    1  
    10   34    2     
    11   23    2      
    12   25    1  
    .   ...    ...  
    n   n    2 
+2

你的問題沒有意義。期望的結果可以幫助在這種情況下。 –

+0

你想寫一個可以這樣做的程序,或者只是想查詢嗎? – ruhul

+0

我只需要查詢 – Tiko

回答

2

有趣的是,雖然有點誤導的問題。這merge爲我工作:

merge into contacts c 
using (
    with t as (
     select c.*, 
       row_number() over (partition by type_id order by id) rn1, 
       row_number() over (partition by type_id order by dbms_random.value) rn2 
      from contacts c) 
    select t1.id, t1.type_id, t1.contact_id, 
      (select contact_id 
       from t t2 where type_id = t1.type_id and rn1 = t1.rn2) as contact_new 
     from t t1) s 
on (c.id = s.id) 
when matched then update set contact_id = s.contact_new; 

起初我產生由type_id分區並下令idrn1)和隨機(rn2)號。你可以看到它分開運行內部查詢。在下一步中,我使用merge中的此查詢作爲源數據。