D.Loo D.Loo - 1 month ago 7
SQL Question

Different case conditions on different rows in same select SQL

I want to do the following

Sel column1,
(CASE WHEN column1=x then 1
ELSE
2
end) AS Key1,
(CASE WHEN column2 =y then 1
CASE WHEN column2 = z then 2
ELSE
3
END) AS Key2
FROM table x


but it gives me Syntax error, expected something like an 'END' keyword between an integer and the 'CASE' keyword. , any clues on how this can be done? How can I use multiple case whens on the same select? I do not want to use subqueries and inner joins.

thanks

Answer

Try this. You got and extra case written in your statement.

Error at this row

CASE WHEN column2 = z then 2

Correct Query

  Sel column1, 
               (CASE WHEN column1=x then 1
               ELSE
               2
               end) AS Key1,
               CASE WHEN column2 =y then 1
               WHEN column2 = z then 2 
               ELSE 
               3
               END) AS Key2
    FROM table x
Comments