我正在寻找编写一个 postgresql 查询来执行以下操作:
if(field1 > 0, field2 / field1 , 0)
我试过这个查询,但它不起作用
if (field1 > 0)
then return field2 / field1 as field3
else return 0 as field3
谢谢你
我正在寻找编写一个 postgresql 查询来执行以下操作:
if(field1 > 0, field2 / field1 , 0)
我试过这个查询,但它不起作用
if (field1 > 0)
then return field2 / field1 as field3
else return 0 as field3
谢谢你
如 PostgreSQL 文档中所述:
SQL CASE 表达式是一个通用的条件表达式,类似于其他编程语言中的 if/else 语句。
专门回答您的问题的代码段:
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
通常,替代case when ...
is 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)