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

后端 未结 7 2148
孤城傲影
孤城傲影 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:54

    Most simplest way is to use a IF(). Yes Mysql allows you to do conditional logic. IF function takes 3 params CONDITION, TRUE OUTCOME, FALSE OUTCOME.

    So Logic is

    if report.type = 'p' 
        amount = amount 
    else 
        amount = -1*amount 
    

    SQL

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

    You may skip abs() if all no's are +ve only

    0 讨论(0)
提交回复
热议问题