SELECT id, amount FROM report
我需要 amount是 amount如果 report.type='P'和 -amount如果 report.type='N'。如何将其添加到上述查询中?
amount
report.type='P'
-amount
report.type='N'
使用case语句:
case
select id, case report.type when 'P' then amount when 'N' then -amount end as amount from `report`
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。
IFNULL(amount,0)
select id, case when report_type = 'P' then amount when report_type = 'N' then -amount else null end from table
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;
SELECT id, amount FROM report WHERE type='P' UNION SELECT id, (amount * -1) AS amount FROM report WHERE type = 'N' ORDER BY id;
最简单的方法是使用IF()。是的,MySQL允许你做条件逻辑。IF函数需要3个参数条件,TRUE OUTCOME,FALSE OUTCOME。
所以逻辑是
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
你可以跳过abs()如果所有的no都是+ve
你也可以试试这个
SELECT id , IF(type='p', IFNULL(amount,0), IFNULL(amount,0) * -1) as amount FROM table