mysql “SELECT”语句中的“IF”-根据列值选择输出值

kxxlusnw  于 2023-04-10  发布在  Mysql
关注(0)|答案(7)|浏览(230)
SELECT id, amount FROM report

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

dphi5xsq

dphi5xsq1#

SELECT id, 
       IF(type = 'P', amount, amount * -1) as amount
FROM report

参见https://dev.mysql.com/doc/refman/8.0/en/flow-control-functions.html
此外,您可以在条件为null时进行处理。在金额为null的情况下:

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

部分IFNULL(amount,0)表示 * 当amount不为null时返回amount else返回0*。

kq0g1dla

kq0g1dla2#

使用case语句:

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

6ss1mwsb3#

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;
brgchamk

brgchamk4#

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

iezvtpos5#

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

如果所有的no都是+ve,你可以跳过abs()

wpcxdonn

wpcxdonn6#

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

UNION

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

ORDER BY id;
wz1wpwve

wz1wpwve7#

你也可以试试这个

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

相关问题