Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android : SQLite : Find closest value from a table

I have a SQLite Database on my app and it is setup like this:

id Value1  Value2
1   12.51    10
2   14.62    20
3   18.94    30
4   21.07    40

I would like to have a code to search on the Value1 column for the closest value to the input and return the value of the same row in the Value2 column.

Example:

I have a variable x=15.12, the code should search for the closest value on Value1 (14.62) and return the respective value from Value2 (20)

Or at least give me the row of the closest value.

How can I achieve this? Thank you very much.

like image 392
Saulo Silva Avatar asked Apr 26 '26 19:04

Saulo Silva


1 Answers

Compute the difference, sort by that value, and take only the first result:

SELECT Value2
FROM MyTable
ORDER BY abs(Value1 - ?)
LIMIT 1

In Android, this would be something like this:

cursor = db.query("MyTable", new String[] { "Value2" },
                  null, null, null, null,
                  "abs(Value1 - " + x + ")", "1");
like image 68
CL. Avatar answered Apr 28 '26 07:04

CL.



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!