【发布时间】:2011-08-22 12:15:09
【问题描述】:
SELECT id, amount FROM report
如果report.type='P' 和-amount 如果report.type='N',我需要amount 是amount。如何将其添加到上述查询中?
【问题讨论】:
SELECT id, amount FROM report
如果report.type='P' 和-amount 如果report.type='N',我需要amount 是amount。如何将其添加到上述查询中?
【问题讨论】:
你也可以试试这个
SELECT id , IF(type='p', IFNULL(amount,0), IFNULL(amount,0) * -1) as amount FROM table
【讨论】:
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。
【讨论】:
sql/item_cmpfunc.h 722: Item_func_ifnull(Item *a, Item *b) :Item_func_coalesce(a,b) {}
IF 语句,有什么问题?
select
id,
case
when report_type = 'P'
then amount
when report_type = 'N'
then -amount
else null
end
from table
【讨论】:
最简单的方法是使用IF()。是的,Mysql 允许你做条件逻辑。 IF 函数需要 3 个参数 CONDITION、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
如果所有的不是 +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 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;
【讨论】:
使用case 声明:
select id,
case report.type
when 'P' then amount
when 'N' then -amount
end as amount
from
`report`
【讨论】:
if report.type = 'P' use amount, otherwise use -amount for anything else。如果不是'P',则不会考虑类型。