SQL使用默认非匹配值的多个键加入

时间:2017-01-07 01:18:05

标签: sql

我需要SQL连接的帮助。

我有以下数据:

 Category Curr     Acct Sales
    A     USD      100  400
    A     INR      123  450
    A     CAD      322  475
    B     EUR      456  230
    B     USD      123  550
    B     GBP      125  900
    X     GBP      399 1000

T2   
Category Curr    Acct Customer
    A     USD       % C01
    A       %     123 C02
    A     CAD     322 C03
    B     USD       % C04
    B       %     456 C05
    B     CAD     555 C06
    B       %       % C07
    %       %       % C08

T1 JOIN T2的预期结果(连接键为Category,Curr和Acct)

T1.Category T1.Curr T1.Acct T1.Sales T2.Customer   
     A         USD    100     400       C01   
     A         INR    123     450       C02   
     A         CAD    322     475       C03   
     B         EUR    456     230       C05   
     B         USD    123     550       C04   
     B         GBP    125     900       C07   
     X         GBP    399    1000       C08   

2 个答案:

答案 0 :(得分:0)

假设%是通配符,则一种方法使用

select t.*,
       (select 
        from t2
        where (t2.category = t.category or t2.category = '%') and
              (t2.curr = t.curr or t2.curr = '%') and
              (t2.acct = t.acct or t2.acct = '%')
        order by ((case when t2.category = '%' then 1 else 0 end) +
                  (case when t2.curr = '%' then 1 else 0 end) +
                  (case when t2.acct = '%' then 1 else 0 end) +
                 ) desc
        fetch first 1 row only
       ) as customer
from t ;

注意:fetch first 1 row only是ANSI SQL。在某些数据库中,它可能拼写为limitselect top 1

答案 1 :(得分:0)

这是一种使用左连接和合并的方法,可以在任何平台上使用。

SELECT T1.Category, T1.Curr, T1.Acct, T1.Sales,
  COALESCE(B.Customer, AWILD.Customer, BWild.Customer, BOTHWILD.Customer, 'NO CUSTOMER FOUND') AS Customer
FROM T1
LEFT JOIN T2 AS B ON T1.Category = B.Category
                 AND T1.Curr = B.Curr 
                 AND T1.Acct = B.Acct
LEFT JOIN T2 AS AWILD ON T1.Category = AWILD.Category 
                     AND T1.Curr = AWILD.Curr 
                     AND AWILDB.Acct = '%'
LEFT JOIN T2 AS CWILD ON T1.Category = CWILD.Category
                     AND CWILD.Curr = '%' 
                     AND T1.Acct = CWILDB.Acct
LEFT JOIN T2 AS BOTHWILD ON T1.Category = BOTHWILD.Category 
                        AND BOTHWILD.Curr = '%' 
                        AND BOTHWILD.Acct = '%'