语句时简化嵌套大小写

时间:2014-05-23 07:15:59

标签: sql postgresql case-when nested-queries multiple-conditions

以下是我当前的SELECT CASE声明:

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

我并不总是想重复版本=' xxx'条件,例如

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

在Excel中这很容易,但我怎样才能在PostgreSQL中编译它?

3 个答案:

答案 0 :(得分:2)

试试这个

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

答案 1 :(得分:1)

您可以在以下情况下嵌套案例。

顺便说一句,当您在单个字段上创建案例时,您可以

case <field> when <value>
             when <otherValue>

而不是

 case when <field> = <value>
      when <field> = <otherValue>

所以

case edition
      when 'STAN'
         case when has9 = 1 then '9'
              when has8 = 1 then '8'
              when has7 = 1 then '7'
              when hasOLD = 1 then 'OLD'
         end
     when 'SUI'
         case when has_s9 = 1 then 'S9'
              when has_s8 = 1 then 'S8'
         end
     else 'S7'
end as version

答案 2 :(得分:1)

Postgres支持both syntax variants for CASE:“简单案例”和“搜索案例”。使用“简单案例”。您还可以嵌套以混合两种变体:

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;

要进一步 ,您可以切换常量变量。两者都只是表达,可以交易Postgres的地方。也许不那么容易阅读和理解,但如果你想要最短的代码......

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;

旁白:CASE statements in plpgsql (the procedural language)的语法略有不同。 (不同的是,真的!)