IF-THEN-ELSE statements in postgresql

后端 未结 3 1797
攒了一身酷
攒了一身酷 2020-12-12 19:02

I\'m looking to write a postgresql query to do the following :

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

I\'ve tried this query, but it\'s no

3条回答
  •  醉话见心
    2020-12-12 19:18

    In general, an alternative to case when ... is coalesce(nullif(x,bad_value),y) (that cannot be used in OP's case). 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)
    

提交回复
热议问题