ChatGPT解决这个技术问题 Extra ChatGPT

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

SELECT id, amount FROM report

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


A
Andrew
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 而不是 COALESCE 是否有任何优势?
从 mysql 源代码中,我注意到了两个 coalesce 定义,一个有 2 个参数,另一个有参数列表,但是 ifnull 使用 2 个参数 sql/item_cmpfunc.h 722: Item_func_ifnull(Item *a, Item *b) :Item_func_coalesce(a,b) {} 调用合并
如果报告类型不同于“N”和“P”,则答案不正确,请参阅 BadHorsie 在更好的“案例陈述”解决方案中的评论。
@Trygve 问题是针对 2 个条件,并在寻找 IF 语句,有什么问题?
@Felipe,答案不一定100%正确,可能还有N和P以外的其他报告类型。在您的情况下,这可能会导致错误,如果报告类型(例如)为“E”,则选择-amount。这个问题没有提到是否有其他报告类型,所以我删除了我的反对票。我只是喜欢在这些情况下进行防御性编程,因此请注意其他读者。
m
mellamokb

使用 case 语句:

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

@埃文:是的。为了清楚起见,我使用它们。并不是说它无论如何都会影响任何事情。
对于特定数据库,我更喜欢 ANSI 标准语法而不是自定义语法。
这是最好的解决方案,因为如果report.type 有其他值,或者以后引入了新的report.type,则接受的答案解决方案不一定合适。它说的是if report.type = 'P' use amount, otherwise use -amount for anything else。如果不是'P',它不会考虑类型。
N
Nikhil
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;

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

a
aWebDeveloper

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


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

UNION

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

ORDER BY id;

由于结果集是互斥的,我更喜欢这里的 UNION ALL。
h
hammythepig

你也可以试试这个

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