3

I need make a decision which table should be use in join statement depend on values in another table

I tried using CASE and COALESCE but can't achieve any success.

  • TableA has A and B and C and many other columns
  • TableB has ID and NAME columns
  • TableC has ID and NAME columns

My select statement is;

Select A.D, A.E, A.F From TableA A

If A.E = 1 then the following join should be used

left outer join TableB B ON A.B = B.ID

and B.NAME should be returned in the select statement

If A.E = 2 then the following join should be used

left outer join TableC C ON A.B = C.ID

and C.NAME should be returned in the select statement

1
  • 2
    Sample data, and expected results, along with your attempt(s) will be really helpful here. Commented Aug 5, 2019 at 21:41

2 Answers 2

4

Just add your conditions to the joins, and then use a case statement to pull the correct field to your result set e.g.

select A.D, A.E, A.F
  , case when B.[Name] is not null then B.[Name] else C.[Name] end [Name]
from TableA A
left outer join TableB B ON A.B = B.ID and A.E = 1
left outer join TableC C ON A.B = C.ID and A.E = 2
Sign up to request clarification or add additional context in comments.

2 Comments

You could also use coalesce() to simplify the case statement since there would never be a case when B.* and C.* are both not null.
Thank you for your answer. Its working very well. Saving my day :)
1

Join tablea with the union of tableb with an extra column with value 1 and tablec with an extra column with value 2 and apply the conditions in the ON clause:

select 
  a.D, a.E, a.F, u.NAME
from tablea a
left join (
  select *, 1 col from tableb
  union all
  select *, 2 col from tablec
) u on a.B = u.id and a.E = u.col  

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.