协慌网

登录 贡献 社区

'SELECT' 语句中的'IF'- 根据列值选择输出值

SELECT id, amount FROM report

如果report.type='P' ,我需要amountamount -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 report

IFNULL(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;