简体   繁体   English

postgresql中的IF-THEN-ELSE语句

[英]IF-THEN-ELSE statements in postgresql

I'm looking to write a postgresql query to do the following : 我正在寻找一个postgresql查询来执行以下操作:

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

I've tried this query, but it's not working 我试过这个查询,但它不起作用

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

thank youu 谢谢你

As stated in PostgreSQL docs here : 如PostgreSQL的文档中阐明在这里

The SQL CASE expression is a generic conditional expression, similar to if/else statements in other programming languages. SQL CASE表达式是一个通用条件表达式,类似于其他编程语言中的if / else语句。

Code snippet specifically answering your question: 代码段专门回答您的问题:

SELECT field1, field2,
  CASE
    WHEN field1>0 THEN field2/field1
    ELSE 0
  END 
  AS field3
FROM test
case when field1>0 then field2/field1 else 0 end as field3

In general, an alternative to case when ... is coalesce(nullif(x,bad_value),y) (that cannot be used in OP's case). 通常, case when ...的替代是coalesce(nullif(x,bad_value),y) (在OP的情况下不能使用)。 For example, 例如,

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

gives: 得到:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM