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

这篇博客讨论了如何在MySQL的SELECT语句中使用IF函数进行条件逻辑判断,特别是在根据列值选择输出值的场景下。通过IF()函数,可以实现当满足特定条件时返回一个值,否则返回另一个值的操作。示例代码和建议被提供,帮助读者理解如何在查询中处理条件判断。
摘要由CSDN通过智能技术生成
SELECT id, amount FROM report

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


#1楼

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

#2楼

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楼

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

UNION

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

ORDER BY id;

#4楼

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

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


#5楼

你也可以尝试一下

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

#6楼

我们来试试这个:

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

#7楼

使用case陈述:

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

#8楼

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)表示金额不为空时返还金额,否则返回0

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值