Nested or multiple case functions

I am trying to do a nested case when query. My table has ID, code1 and code2 columns.
create table as select ID, code1 case when code1 is not null then 'yes' else (select code2, case when code 2 is not null then 'no' else 'NA' from table) from table

What I want to achieve is that if code1 is null, I want to go ahead and check for code2 being null or not null. If code1 is not null then it gets a tag ‘yes’ right away without any checks on code2.
What would be the right way to do this. Any help would be appreciated. Thanks.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You only need 1 CASE expression:

SELECT ID, code1,
       CASE 
         WHEN code1 IS NOT NULL THEN 'yes' 
         WHEN code2 IS NOT NULL THEN 'no'
         ELSE 'NA'
       END AS tag
FROM tablename

Each WHEN branch is processed only if the previous ones failed.

Method 2

Combined with creating a table, you get the id and a tag with your specification

CREATE TABLE mynewtable SELECT ID,
    CASE
        WHEN code1 IS NOT NULL THEN 'yes'
        WHEN code2 IS NOT NULL THEN 'no'
        ELSE 'NA'
    END tag FROM
    table1


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x