Search Postgresql Archives

Re: Finding nearest numeric value

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



To find the nearest value in number_column to some CONSTANT (where you
replace constant with a number), try:

select *,(number_column - CONSTANT)^2 as d from tablename order by d limit
1;

Does that do it for you?

Sean



It does ideed, not that I understood how, but I will find out.
Thank you very much.


Just a word (or several) of explanation, then....

To compute the distance between two points on a line, you can compute the
absolute value of the difference (4-2 is the same distance as 2-4, while the
latter is negative) or you can square the difference (just to make it
positive).  You could use absolute value in the above query if you like--I
don't know which is faster, but they will give the same result.

As for the query structure, you can select calculations of columns as well
as the columns themselves.  The "as d" part just gives the calculation a
nice name to use in the rest of the query and in the resulting output.

Sean


Thanks for the explanation, guess I was fast giving up understanding the query as it is actually quite simple :)

Of course there are the performance issues as argued by others, but the table do only contain around 800 rows, so this method is adequate.

Thank you all for the inputs.


Poul

---------------------------(end of broadcast)---------------------------
TIP 1: if posting/reading through Usenet, please send an appropriate
      subscribe-nomail command to majordomo@xxxxxxxxxxxxxx so that your
      message can get through to the mailing list cleanly

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
[Index of Archives]     [Postgresql Jobs]     [Postgresql Admin]     [Postgresql Performance]     [Linux Clusters]     [PHP Home]     [PHP on Windows]     [Kernel Newbies]     [PHP Classes]     [PHP Books]     [PHP Databases]     [Postgresql & PHP]     [Yosemite]
  Powered by Linux