私は以下を行うために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
AS
命令は必要ありません。あなたはこれを行うことができますEND field3
case when field1>0 then field2/field1 else 0 end as field3
一般に、の代替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