2014-07-18 40 views
0

我有一張表,產品中的產品列表。這可能包含超過500萬條記錄。使用查找表中的值更新列

prod_code prod_region  prod_desc  prod_type 
------------------------------------------------------ 
1001  R2    r2 asdasa 
1001  R1    r1 erfffv 
1002  R4    r4 vfdser 
1003  R2    r2 sdfdfv 

prod_code和prod_region不能爲空。

我需要更新此表中的prod_type,從另一個查找表中選擇product_type。

prod_type prod_code prod_region 
----------------------------------- 
1   1001 
2   1002 
2   1003 
3   1001  R1 

在此表中,prod_region可以爲null。如果它是空的,它應該被解釋爲Anything。

所以我的更新產品表應該是,

prod_code prod_region  prod_desc  prod_type 
------------------------------------------------------ 
1001  R2    r2 asdasa  1  
1001  R1    r1 erfffv  3 
1002  R4    r4 vfdser  2 
1003  R2    r2 sdfdfv  2 

所需的輸出的說明。

  1. 對於prod_code = 1001,product_type中有兩個條目。對於其他區域,prod_type = 3對於特定prod_region'R1'和prod_type = 1。 因此,產品中的前兩個記錄應該分別得到1和3。
  2. 對於prod_code 1002,1003,沒有在product_type表中指定prod_region。所以第三和第四條記錄被分配prod_type = 2,與prod_region無關。

以下合併聲明因Oracle中的ORA-30926: unable to get a stable set of rows in the source tables或Teradata中的Failure 7547 Target row updated by multiple source rows.而失敗。

merge into products 
using product_type 
on (products.prod_code = product_type.prod_code 
    and products.prod_region = coalesce(product_type.prod_region,products.prod_region) 
    ) 
when matched then update 
set products.prod_type = product_type.prod_type; 

尋找標準的SQL或Teradata的具體答案。

回答

1

而是一個複雜的語句,你可能在兩個簡單的合併將它分割:

merge into products 
using product_type 
    on products.prod_code = product_type.prod_code 
    and product_type.prod_region is null 
when matched then update 
set prod_type = product_type.prod_type; 

merge into products 
using product_type 
    on products.prod_code = product_type.prod_code 
    and products.prod_region = product_type.prod_region 
when matched then update 
set prod_type = product_type.prod_type; 
1

怎麼是這樣的:

update products 
set prod_type = (
    select T.prod_type 
    from product_type T 
    where T.prod_code = products.prod_code 
    and (
     T.prod_region = product.prod_region 
     or (
      T.prod_region is null 
      and not exists (
       select 1 
       from product_type T2 
       where T2.prod_code = products.prod_code 
       and T2.prod_region = product.prod_region 
      ) 
     ) 
    ) 
) 

儘管人們可能會質疑德正常化您的數據是這樣的原因。