【问题标题】:IF-THEN-ELSE statements in postgresqlpostgresql 中的 IF-THEN-ELSE 语句
【发布时间】:2013-09-26 13:35:21
【问题描述】:

我希望编写一个 postgresql 查询来执行以下操作:

if(field1 > 0,  field2 / field1 , 0)

我试过这个查询,但它不起作用

if (field1 > 0)
then return field2 / field1 as field3
else return 0 as field3

谢谢你

【问题讨论】:

标签: sql postgresql


【解决方案1】:

如 PostgreSQL 文档 here 中所述:

SQL CASE 表达式是一个通用条件表达式,类似于其他编程语言中的 if/else 语句。

代码 sn-p 专门回答您的问题:

SELECT field1, field2,
  CASE
    WHEN field1>0 THEN field2/field1
    ELSE 0
  END 
  AS field3
FROM test

【讨论】:

  • 出于好奇,难道没有使用 if-then-else 语句的解决方案吗?问题要求 if-then-else 但答案是 switch-case 语句。
  • 嗨,Abel,这个问题要求解决特定问题。答案解决了该特定问题。在SELECT 语句中,您可以使用的条件(其中一个是CASE)记录在here 中。
  • 在这种情况下,如果您在答案中添加更困难的原因或使用 if-then 语句无法实现此目的的原因,则会更清楚。
  • @MaximilianoBecerra 完成。请看一下。感谢您的建议。
  • AS 指令不是必需的。你可以这样做END field3
【解决方案2】:
case when field1>0 then field2/field1 else 0 end as field3

【讨论】:

    【解决方案3】:

    一般来说,case when ... 的替代品是coalesce(nullif(x,bad_value),y)(不能在 OP 的情况下使用)。例如,

    select coalesce(nullif(y,''),x), coalesce(nullif(x,''),y), *
    from (     (select 'abc' as x, '' as y)
     union all (select 'def' as x, 'ghi' as y)
     union all (select '' as x, 'jkl' as y)
     union all (select null as x, 'mno' as y)
     union all (select 'pqr' as x, null as y)
    ) q
    

    给予:

     coalesce | coalesce |  x  |  y  
    ----------+----------+-----+-----
     abc      | abc      | abc | 
     ghi      | def      | def | ghi
     jkl      | jkl      |     | jkl
     mno      | mno      |     | mno
     pqr      | pqr      | pqr | 
    (5 rows)
    

    【讨论】:

    • 有时我不想要 case when 的壮观场面,这符合要求
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-11
    • 2016-08-30
    • 2015-11-18
    相关资源
    最近更新 更多