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?
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 |
The DIFFERENCE() function compares two SOUNDEX values, and returns an integer. The integer value indicates the match for the two SOUNDEX values, from 0 to 4. 0 indicates weak or no similarity between the SOUNDEX values. 4 indicates strong similarity or identically SOUNDEX values.
To count the difference between dates in MySQL, use the DATEDIFF(enddate, startdate) function. The difference between startdate and enddate is expressed in days. In this case, the enddate is arrival and the startdate is departure .
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:
SELECT numberA, numberB
FROM table
ORDER BY ABS(numberA - numberB) DESC
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With