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 は null 許容ではありません。

別のルックアップ テーブル product_type から選択して、このテーブルの prod_type を更新する必要があります。

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

このテーブルでは、prod_region は null にすることができます。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 に 2 つの整数があります。特定の prod_region 'R1' の場合は prod_type = 3、残りの地域の場合は prod_type = 1 です。したがって、products の最初の 2 つのレコードは、それぞれ 1 と 3 を取得する必要があります。
  2. prod_code 1002、1003 の場合、product_type テーブルに prod_region が指定されていません。したがって、prod_region に関係なく、3 番目と 4 番目のレコードには prod_type = 2 が割り当てられます。

次のマージ ステートメントはORA-30926: unable to get a stable set of rows in the source tables、Oracle またはFailure 7547 Target row updated by multiple source rows.Teradata が原因で失敗します。

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 固有の回答を探しています。

4

2 に答える 2

1

1 つの複雑なステートメントの代わりに、2 つの単純な MERGE に分割できます。

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;
于 2014-07-18T06:46:37.240 に答える
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
            )
        )
    )
)

このようにデータを非正規化する理由を疑問視する人もいるかもしれませんが。

于 2014-07-18T06:23:57.913 に答える