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

时间:2011-05-10 13:53:31

标签: mysql sql database

SELECT id, amount FROM report

如果amount我需要amount report.type='P' -amount report.type='N'如何将其添加到上述查询?

8 个答案:

答案 0 :(得分:979)

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

答案 1 :(得分:238)

使用case声明:

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

答案 2 :(得分:93)

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;

答案 3 :(得分:37)

select 
  id,
  case 
    when report_type = 'P' 
    then amount 
    when report_type = 'N' 
    then -amount 
    else null 
  end
from table

答案 4 :(得分:14)

最简单的方法是使用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

如果所有不是仅+ +

,您可以跳过abs()

答案 5 :(得分:11)

SELECT id, amount
FROM report
WHERE type='P'

UNION

SELECT id, (amount * -1) AS amount
FROM report
WHERE type = 'N'

ORDER BY id;

答案 6 :(得分:4)

让我们试试这个:

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

答案 7 :(得分:2)

你也可以尝试这个

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