How to find the closest match in a CommCare Lookup Table

commcare

Is it possible to lookup the closest value (equal or less than) to a particular question using a Lookup Table in CommCare?

Example:
My table has values 5, 6.35, 42.8, 136. I want an input of 6 to return 5, 6.35 to return 6.35, 48 to return 42.8, and 135 to return 42.8.

Best Answer

I believe you can use <= in a filter in combination with max to achieve this affect.

The xpath might look something like this

max(instance('myentrys')/myentry_list/myentry[value <= target_value]/value)

That will give you the maximum value less than target_value. If what you wanted was the entire row in the table that has that value, you can then do a lookup on that value—i.e. find the row that has the value that is the maximum value less than target_value:

instance('myentrys')/myentry_list/myentry/value[value =
    max(instance('myentrys')/myentry_list/myentry[value <= target_value]/value)]