Below is my current SELECT CASE statement:
SELECT CASE
WHEN edition = 'STAN' AND has9 = 1 THEN '9'
WHEN edition = 'STAN' AND has8 = 1 THEN '8'
WHEN edition = 'STAN' AND has7 = 1 THEN '7'
WHEN edition = 'STAN' AND hasOLD = 1 THEN 'OLD'
WHEN edition = 'SUI' AND has_s9 = 1 THEN 'S9'
WHEN edition = 'SUI' AND has_s8 = 1 THEN 'S8' ELSE 'S7' END AS version
I do not always want to repeat the edition = 'xxx' condition, such as
CASE WHEN edition = 'STAN' AND has9 = 1 THEN '9' ELSE WHEN has8 = 1 THEN '8' ELSE WHEN has7 = '7' ELSE WHEN edition 'SUI' AND has_s9 = 1 THEN 'S9' ELSE ...
In Excel this is fairly easy but how can I compile that in PostgreSQL?
Postgres supports both syntax variants for
CASE
: the "simple CASE" and the "searched CASE". Use a "simple CASE". And you can also nest to mix both variants:To carry this one step further , you can switch constant and variable. Both are just expressions and can trade places in Postgres. Maybe not as easy to read and understand, but if you want the shortest code ...
Aside: The syntax for
CASE
statements in plpgsql (the procedural language) is slightly different. (Different thing, really!)Try this
You can nest your case when.
By the way, when you make a case on a single field, you can do
rather then
So