Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the value closest to zero using SQL Server

Let's say I have a table that could have various numbers in it, for example it could look like the following:

ExampleA: MyTable -10, -3, 5, 10,

ExampleB: MyTable -10, -5, 3, 10,

So if I queried the table in ExampleA I'd want it to return "-3" (The value closet to 0)

Likewise if I queried the table in ExampleB I'd want it to return "3" (The value closest to 0)

I always want to find the value that is closest to zero regardless of the numbers in the table, how can I do this?

Also, how could I choose which value for ties (like in the case where the closest value may be -3 and 3)?

like image 807
user2989991 Avatar asked Oct 26 '25 08:10

user2989991


1 Answers

Use a combination of min() and abs():

select num
from mytable
where abs(num) = (select min(abs(num)) from mytable)

To break ties, apply min() or max() to num to get the negative or positive side, eg

To get the negative of a tie:

select min(num) num 
from mytable
where abs(num) = (select min(abs(num)) from mytable)

To get the positive of a tie:

select max(num) num
from mytable
where abs(num) = (select min(abs(num)) from mytable)
like image 129
Bohemian Avatar answered Oct 28 '25 23:10

Bohemian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!