sqllogicsql-scriptshana-sql-scripthana-studio

Conditional SQL queries with SQL Script


I have two example tables:

TABLE1:
      ID    | COLUMN_B| COLUMN_C
   _________|_________|_________
       1    |    0    |    1
    ________|_________|_________
       2    |    0    |    1
    ________|_________|_________
       3    |    0    |    1


    TABLE2:
      ID    | COLUMN_E| COLUMN_F
    ________|_________|________
       1    |    Y    |    X
    ________|_________|_________
       2    |    Y    |    X
    ________|_________|_________
       3    |    Y    |    X

They relate to each other with the ID column. I would like to perform a select on TABLE1, bringing COLUMN_B and bringing COLUMN_C only if the value on COLUMN_E is Y.

Is it possible to create a condition that simulates something like: "select column_b, and select column_c IF AND ONLY IF the value on column_e from TABLE2 is Y for the same ID"?


Solution

  • If I understand correctly, this is just a case expression:

    select t1.column_b,
           (case when t2.column_e = 'Y' then t1.column_c end) as column_c
    from table1 t1 left join
         table2 t2
         on t1.id = t2.id;