postgresql中的IF-THEN-ELSE语句

时间:2013-09-26 13:35:21

标签: sql postgresql

我正在寻找一个postgresql查询来执行以下操作:

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

我已经尝试过此查询,但它无效

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

谢谢你

3 个答案:

答案 0 :(得分:98)

如PostgreSQL docs here中所述:

  

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

专门回答您问题的代码段:

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

答案 1 :(得分:15)

case when field1>0 then field2/field1 else 0 end as field3

答案 2 :(得分:0)

通常,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)