简体   繁体   中英

SQL Left Join - OR clause

I am trying to join two tables. I want to join where all the three identifiers (Contract id, company code and book id) are a match in both tables, if not match using contract id and company code and the last step is to just look at contract id

Can the task be performed wherein you join using all three parameters, if does not, check the two parameters and then just the contract id?

Code:

SELECT * 
INTO   #prem_claim_wtauto_test 
FROM   #contract_detail A 
       LEFT JOIN #claim_total C 
              ON ( ( C.contract_id_2 = A.contract_id 
                     AND C.company_cd_2 = A.company_cd 
                     AND C.book_id_2 = A.book_id ) 
                    OR ( C.contract_id_2 = A.contract_id 
                         AND C.company_cd_2 = A.company_cd ) 
                    OR ( C.contract_id_2 = A.contract_id ) ) 

Your ON clause boils down to C.contract_id_2 = A.contract_id . This gets you all matches, no matter whether the most precise match including company and book or a lesser one. What you want is a ranking. Two methods come to mind:

  1. Join on C.contract_id_2 = A.contract_id , then rank the rows with ROW_NUMBER and keep the best ranked ones.
  2. Use a lateral join in order to only join the best match with TOP .

Here is the second option. You forgot to tell us which DBMS you are using. SELECT INTO looks like SQL Server. I hope I got the syntax right:

SELECT * 
INTO   #prem_claim_wtauto_test 
FROM   #contract_detail A 
OUTER APPLY
(
  SELECT TOP(1) *
  FROM #claim_total C 
  WHERE C.contract_id_2 = A.contract_id
  ORDER BY 
    CASE 
      WHEN C.company_cd_2 = A.company_cd AND C.book_id_2 = A.book_id THEN 1
      WHEN C.company_cd_2 = A.company_cd THEN 2
      ELSE 3
    END
);

If you want to join all rows in case of ties (eg many rows matching contract, company and book), then make this TOP(1) WITH TIES .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM