'IF' in 'SELECT' statement - choose output value based on column values

后端 未结 7 2156
孤城傲影
孤城傲影 2020-11-22 04:24
SELECT id, amount FROM report

I need amount to be amount if report.type=\'P\' and -amount if

7条回答
  •  情深已故
    2020-11-22 04:39

    SELECT id, 
           IF(type = 'P', amount, amount * -1) as amount
    FROM report
    

    See http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html.

    Additionally, you could handle when the condition is null. In the case of a null amount:

    SELECT id, 
           IF(type = 'P', IFNULL(amount,0), IFNULL(amount,0) * -1) as amount
    FROM report
    

    The part IFNULL(amount,0) means when amount is not null return amount else return 0.

提交回复
热议问题