SELECT id, amount FROM report如果report.type='P' ,我需要amount为amount -amount如果report.type='N'我需要金额为 - amount。如何将此添加到上面的查询中?
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 。
此外,您可以处理条件为 null 的情况。如果为零,则:
SELECT id,
IF(type = 'P', IFNULL(amount,0), IFNULL(amount,0) * -1) as amount
FROM reportIFNULL(amount,0)表示,当金额不为 null 时,返回金额,否则返回 0 。
使用一个case语句:
select id,
case report.type
when 'P' then amount
when 'N' then -amount
end as amount
from
`report`
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;