SELECT id, amount FROM report

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


当前回答

最简单的方法是使用IF()。是的,Mysql允许你做条件逻辑。IF函数有3个参数:条件,真结果,假结果。

逻辑就是

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

如果所有的no都是+ve,你可以跳过abs()

其他回答

你也可以试试这个

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

最简单的方法是使用IF()。是的,Mysql允许你做条件逻辑。IF函数有3个参数:条件,真结果,假结果。

逻辑就是

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

如果所有的no都是+ve,你可以跳过abs()

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,
  case 
    when report_type = 'P' 
    then amount 
    when report_type = 'N' 
    then -amount 
    else null 
  end
from table

使用case语句:

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