博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
'SELECT'语句中的'IF' - 根据列值选择输出值
阅读量:3578 次
发布时间:2019-05-20

本文共 1431 字,大约阅读时间需要 4 分钟。

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   endfrom table

#2楼

SELECT CompanyName,     CASE WHEN Country IN ('USA', 'Canada') THEN 'North America'         WHEN Country = 'Brazil' THEN 'South America'         ELSE 'Europe' END AS ContinentFROM SuppliersORDER BY CompanyName;

#3楼

SELECT id, amountFROM reportWHERE type='P'UNIONSELECT id, (amount * -1) AS amountFROM reportWHERE type = 'N'ORDER BY id;

#4楼

最简单的方法是使用 。 是的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 amountFROM  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 amountfrom    `report`

#8楼

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

请参阅 。

此外,您可以在条件为null时进行处理。 在空金额的情况下:

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

部分IFNULL(amount,0)表示金额不为空时返还金额,否则返回0

转载地址:http://deogj.baihongyu.com/

你可能感兴趣的文章
springboot+mybatis实现分页
查看>>
为什么局域网网段不同不能通信?
查看>>
认识和使用JWT
查看>>
条件表达式于运算符的点点滴滴的积累
查看>>
最短路径最基本的三种算法【此后无良辰】
查看>>
class的点点滴滴的总结
查看>>
vector 的点点滴滴的总结
查看>>
测试用例
查看>>
自动化测试学习步骤
查看>>
自动化测试需要掌握的知识
查看>>
HTTP协议
查看>>
Python小程序——冒泡排序
查看>>
cmd中输入net start mysql 提示:服务名无效或者MySQL正在启动 MySQL无法启动
查看>>
LeetCode 206反转链表 [javsScript]
查看>>
[LeetCode javaScript] 3. 无重复字符的最长子串
查看>>
[LeetCode javaScript] 6. Z字形变换
查看>>
[LeetCode javaScript]455. 分发饼干
查看>>
[LeetCode javaScript] 735. 行星碰撞
查看>>
[LeetCode javaScript] 125. 验证回文串
查看>>
[LeetCode javaScript] 226. 翻转二叉树
查看>>