IF-THEN-ELSE statements in postgresql

后端 未结 3 1784
攒了一身酷
攒了一身酷 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)
    
    0 讨论(0)
  • 2020-12-12 19:20
    case when field1>0 then field2/field1 else 0 end as field3
    
    0 讨论(0)
  • 2020-12-12 19:33

    As stated in PostgreSQL docs here:

    The SQL CASE expression is a generic conditional expression, similar to if/else statements in other programming languages.

    Code snippet specifically answering your question:

    SELECT field1, field2,
      CASE
        WHEN field1>0 THEN field2/field1
        ELSE 0
      END 
      AS field3
    FROM test
    
    0 讨论(0)
提交回复
热议问题