MySQL MYSQL如何求两个数的绝对差

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23835268/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 20:33:13  来源:igfitidea点击:

How to find absolute difference between two numbers MYSQL

mysql

提问by user1145643

What's the best way to find the absolute difference between two numbers in MYSQL so that I may order results? The below works, only if numberA is larger than numberB, but as you can see this is not always the case. Is there a good way to do this with one statement?

在 MYSQL 中找到两个数字之间的绝对差以便我可以对结果进行排序的最佳方法是什么?以下仅当 numberA 大于 numberB 时才有效,但正如您所见,情况并非总是如此。有没有一种好方法可以用一个语句来做到这一点?

SELECT (numberA - numberB) AS spread 
FROM table 
ORDER BY spread DESC

|-------------------|
| numberA | numberB |
| 5.4     | 2.2     |
| 7.7     | 4.3     |
| 1       | 6.5     |
| 2.3     | 10.8    |
| 4.5     | 4.5     |

回答by John Bupit

As simple as that:

这么简单:

SELECT ABS(numberA - numberB) AS spread 
FROM table 
ORDER BY spread DESC

Or, if you want to select the pair (numberA, numberB) in descending order of their difference:

或者,如果您想按差异的降序选择对 (numberA, numberB)

SELECT numberA, numberB
FROM table 
ORDER BY ABS(numberA - numberB) DESC

回答by juergen d

MySQL has an ABS()function for that:

MySQL 有一个ABS()函数:

select abs(numberA - numberB) as abs_diff
from your_table
ORDER BY abs_diff DESC