简体   繁体   中英

SQL join tables based on if else if conditions

New to doing SQL stuff so please excuse me.

I want to create a SQL query that joins a column to table A from table B based on the following match logic:

B.Source = ‘SOURCE1’ and A.NameCode= B.Code

If the above return NULL then I'd like to match on:

B.Source <> ‘SOURCE1’ and A.UEN = B.UEN**

Any help on how to structure this? I currently have a union all select query that can get the values based on the above conditions. Should I be using an If/or/case_when in the join process?

A few questions in which I thought could be helpful and that I've looked at are:

How to perform a LEFT JOIN in SQL Server between two SELECT statements?

Using IS NULL or IS NOT NULL on join conditions - Theory question

But I was not able to come up with anything :( Thank you so much!

Try something like this:

SELECT * 
FROM A
JOIN B ON (
    (B.Source = 'Source1' AND A.NameCode = B.Code) OR
    (B.Source <> 'Source1' AND A.UEN = B.[UEN**]) --Not sure what the ** is?  Part of the field name?
)

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