1

Is CASE expression allowed in join? Is there a good way to accomplish the task here? My real query has some other left join.

I would like to join T1 and T2 in this condition:

  1. when T1.sub_service is not null, then join with T2.type

  2. when T1.sub_service is null, then use T1.service to join with T2.type

    SELECT T1.service, T1.sub_service, T2.type FROM TABLE1 T1 LEFT JOIN TABLE2 T2 ON T2.type LIKE CASE WHEN T1.sub_service IS NULL THEN T1.service WHEN T1.sub_service IS NOT NULL THEN T1.sub_service END

1 Answer 1

4

Simply replace the LIKE with =:

ON T2.type = 
   CASE WHEN T1.sub_service IS NULL THEN T1.service
        WHEN T1.sub_service IS NOT NULL THEN T1.sub_service
   END

But you can further simplify this to a COALESCE:

ON T2.type = COALESCE(T1.sub_service, T1.service)
Sign up to request clarification or add additional context in comments.

7 Comments

Can I use "like" instead of "=" because there are some type I need to use "like" in order to get match some types.
I don't understand. Can you show some examples what you actually try to do?
I changed the query to "ON COALESCE(T1.sub_service, T1.service) LIKE T2.type" and it works. I get the right result. Thanks a lot for help!
If this is your actual condition it's the same as using equality (unless there are some trailing blanks), but might result in a bad plan.
Teradata doesn't ignore trailing blanks in a join?
|

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.