4

以下是我当前的 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

我并不总是想重复 edition = '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 中编译它?

4

3 回答 3

3

试试这个

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
于 2014-05-23T07:21:13.593 回答
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
于 2014-05-23T07:21:30.997 回答
1

Postgres 支持两种语法变体CASE:“simple CASE”和“searched 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另外: plpgsql(过程语言)中语句的语法略有不同。(不同的东西,真的!)

于 2014-05-24T00:08:36.783 回答