2016-06-22 2 views
1

カラム優先度に基づいて2つのテーブルを結合したいカラムベースの結合

ex。そうでない場合は

私は表2(のCol1、Col2に、COL3、COL4、COL5、COL7)を表1に参加したい場合は、それが必要表1は、6つの列(のCol1、Col2に、COL3、COL4、COL5、COL6) を持っていると仮定

Select Table2.col7 
where 
first check col1 , col2 and col3 if match found no need go check more 
second check col1 , col2 if match found no need go check more 
third check col1 if match found no need go check more 
last ignore all col1 , col2 and col3 
AND Table1.Col4=Table2.Col4 
AND Table1.Col5=Table2.Col5 

任意の懸念が

+0

「AND」の代わりに「OR」を使用してください。一致が見つかった場合、他の条件はチェックされません。 – Dany

+0

(!!!)UPD:間違っています:http://stackoverflow.com/questions/8900631/does-oracle-use-short-circuit-evaluation – Dany

答えて

0
Select t2.col7 
    from Table1 t1 inner join Table2 t2 
    on 
    case 
    when t1.col1 = t2.col1 then 1 
    when t1.col2 = t2.col2 then 1 
    when t1.col3 = t2.col3 then 1 
    when t1.Col4=t2.Col4 
     and t1.Col5=t2.Col5 then 1 
    else 0 end = 1 
    ; 
+0

@ user6498752私は編集しました答え。それがあなたが探しているものかどうかを教えてください – vercelli

+0

あなたの時間はおかげでVercelliありがとうございますが、もう1つの問題があります。選択はt1.col4とt1.col5の値に基づいていなければなりません。 (A、1)、(A、0)、(B、0)の組み合わせには4つのオプションがあります。 、(B、1)組み合わせごとに、それが次にチェック 場合t1.col1 = t2.col1次いで1 t1.col2 = t2.col2次いで1 t1.col3 = t2.col3以下のために行きます1 else 0 end = 1 私はすぐにこのことについても手伝ってくれます...多くのありがとうございます。 – user6498752

+0

@vercelli: 'CASE'式はWHERE句には含まれていません。代わりに単純な 'AND'と' OR'を使用してください。 –

0
あなたが最初のケースでは、それは上に行くための一致を検出できなかった特定の条件に参加しようとするSQLを言うことができない

を叫ぶください場合、私は、私の言葉で明確ではないかもしれません検索。あなたができることは、許可されたすべての組み合わせ(自分の場合はcol4とcol5の一致)を結合し、一致するものをランク付けすることです(col1とcol2とcol3の一致が最も良いとみなされます)。

select col7 
from 
(
    select 
    t1.*, 
    t2.*, 
    row_number() over 
    (
     partition by t1.col4, t1.col5 
     order by case 
     when t2.col1 = t1.col1 and t2.col2 = t1.col2 and t2.col3 = t1.col3 then 1 
     when t2.col1 = t1.col1 and t2.col2 = t1.col2 then 2 
     when t2.col1 = t1.col1 then 3 
     else 4 
    ) as rn 
    from table1 t1 
    join table2 t2 on t2.col4 = t1.col4 and t2.col5 = t1.col5 
) 
where rn = 1; 
+0

ありがとうThorstenとVercelli、私はコードの下で実行しようとしているが、エラー を投げて、私はもう1つのテーブルを導入しました。 – user6498752

+0

選択DISTINCT CU.ID cu_id、 'XXXX'、to_char(RR.EFF_FROM、 'DD-MON-YYYY')Active_Date、NVL(to_char(RR.EFF_TO、 'DD-MON-YYYY')、'31 -DEC- 9999' RR.Divi_Flag、場合によって RR.Brand_Type_CodeためRR.Dept_Cd = FLOORによる)Inactive_Date から( 選択RL *、CU *、RR *、 ROW_NUMBER() ( 上パーティション(RR.Sub_Section/10000)およびRR.Section = FLOOR(MOD(RL.Sub_Section、10000)/ 100)およびRR.SubSection = MOD(RL.Sub_Section、100)である場合、1 となる。 Sub_Section/10000)とRR.Section = FLOOR(MOD(RL.Sub_Section、10000)/ 100)の場合は2 – user6498752

+0

、RR.Dept_Cd = FLOOR(RL.Sub_Section/10000)ならば3 else 4 )は、表1 RLから として、 として表2CUの RRとなる。ここで、RL.Code = CUである。FK_Rl_Code AND RL.Brand_Type_Code = RR.Brand_Type_Code とNVL(CU.Dividend_Flag、 'X')= NVL(RR.Divi_Flag、 'X')はcu.skeletal_full_indは= 'F' AND cu.discontinued_dateがnullである WHERE ) ここで、rn = 1; – user6498752