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

后端 未结 7 2190
孤城傲影
孤城傲影 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:32
    select 
      id,
      case 
        when report_type = 'P' 
        then amount 
        when report_type = 'N' 
        then -amount 
        else null 
      end
    from table
    
    0 讨论(0)
  • 2020-11-22 04:38
    SELECT id, amount
    FROM report
    WHERE type='P'
    
    UNION
    
    SELECT id, (amount * -1) AS amount
    FROM report
    WHERE type = 'N'
    
    ORDER BY id;
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 04:46
    SELECT CompanyName, 
        CASE WHEN Country IN ('USA', 'Canada') THEN 'North America'
             WHEN Country = 'Brazil' THEN 'South America'
             ELSE 'Europe' END AS Continent
    FROM Suppliers
    ORDER BY CompanyName;
    
    0 讨论(0)
  • 2020-11-22 04:49

    You can try this also

     SELECT id , IF(type='p', IFNULL(amount,0), IFNULL(amount,0) * -1) as amount FROM table
    
    0 讨论(0)
  • 2020-11-22 04:51

    Use a case statement:

    select id,
        case report.type
            when 'P' then amount
            when 'N' then -amount
        end as amount
    from
        `report`
    
    0 讨论(0)
提交回复
热议问题