Simplify nested case when statement

前端 未结 3 872
你的背包
你的背包 2021-01-06 04:25

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          


        
3条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-06 05:31

    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:

    SELECT CASE edition 
           WHEN 'STAN' THEN 
              CASE WHEN has9 = 1 THEN '9'
                   WHEN has8 = 1 THEN '8'
                   WHEN has7 = 1 THEN '7' 
                   WHEN hasOLD = 1 THEN 'OLD'
                   -- no ELSE means ELSE NULL
              END
           WHEN 'SUI' THEN
              CASE WHEN has_s9 = 1 THEN 'S9' 
                   WHEN has_s8 = 1 THEN 'S8'
              END  -- no ELSE means ELSE NULL
           ELSE 'S7'
           END AS version;
    

    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 ...

    SELECT CASE edition 
           WHEN 'STAN' THEN 
              CASE 1
              WHEN has9   THEN '9'
              WHEN has8   THEN '8'
              WHEN has7   THEN '7' 
              WHEN hasOLD THEN 'OLD'
              END
           WHEN 'SUI' THEN
              CASE 1
              WHEN has_s9 THEN 'S9' 
              WHEN has_s8 THEN 'S8'
              END
           ELSE 'S7'
           END AS version;
    

    Aside: The syntax for CASE statements in plpgsql (the procedural language) is slightly different. (Different thing, really!)

提交回复
热议问题