Search code examples
sqlpostgresqlcase

how to set value in other column while using case statement in SQL


I creating different labels for my column, depending on various conditions. And it looks like this:

, CASE
    WHEN phone like '%555%' THEN 1
    ELSE 0
END AS first_label

, CASE
    WHEN phone like '%888%' THEN 1
    ELSE 0
END AS second_label

But also i need to name this new lable in new column like lable name = 'first_label' for each row. So how can i do it whithout copying that blocks again? My result:

SELECT 
, phone    
, CASE
    WHEN phone like '%555%' THEN 1
    ELSE 0
END AS first_label
, CASE
    WHEN phone like '%888%' THEN 1
    ELSE 0
END AS second_label
, 'lable_name' as lable_name

FROM mytable

expected output:

phone first_label second_label lable_name
555 75 71 1 1 0 first_label
888 94 18 3 0 1 second_label

Solution

  • In order not to repeat the expressions again, simply select from your query result. E.g.:

    WITH labeled AS
    (
      SELECT 
        phone, 
        CASE WHEN phone like '%555%' THEN 1 ELSE 0 END AS first_label,
        CASE WHEN phone like '%888%' THEN 1 ELSE 0 END AS second_label
      FROM mytable
    )
    SELECT
      phone,
      first_label,
      second_label,
      CASE
        WHEN first_label = 1 AND second_label = 1 THEN 'both labels'
        WHEN first_label = 1 AND second_label = 0 THEN 'first_label'
        WHEN first_label = 0 AND second_label = 1 THEN 'second_label'
        ELSE                                           'no label'
      END AS label_names
    FROM labeled;
    

    Demo: https://dbfiddle.uk/zwDO1N1Q