SELECT id, amount FROM report

我需要金额是金额,如果报告。如果report.type='N',则type='P'和-amount。我如何将此添加到上面的查询?


当前回答

使用case语句:

select id,
    case report.type
        when 'P' then amount
        when 'N' then -amount
    end as amount
from
    `report`

其他回答

你也可以试试这个

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

UNION

SELECT id, (amount * -1) AS amount
FROM report
WHERE type = 'N'

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

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

此外,您还可以处理条件为空的情况。如果是空值:

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

IFNULL(amount,0)部分表示当金额不为空时返回金额,否则返回0。

使用case语句:

select id,
    case report.type
        when 'P' then amount
        when 'N' then -amount
    end as amount
from
    `report`
select 
  id,
  case 
    when report_type = 'P' 
    then amount 
    when report_type = 'N' 
    then -amount 
    else null 
  end
from table