Returning the closest match to a criteria

Hello,

Is there a way in Access to return a value which is the closest to my criteria?  
example:  select field_1 where field_1= 3.77 (if there is no match return the closest either lower or higher to 3.77)

Thanks
afking8268Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

peter57rCommented:
Hi afking8268,

You can do this: (fix the field names and drop it into the SQL view of  a query):
select * from mytable where Abs([field_1]-3.77) in
(SELECT Min(Abs([field_1]-3.37)) AS Expr1
FROM mytable)

Pete
NatchiketCommented:
SELECT TOP 1 Field_1  FROM table ORDER BY Abs(field_1-3.77)
thenelsonCommented:
How about:

Function ReturnClosestValue (ValueIn As Single) As Single
Dim ClosestUnder As Single, ClosestOver As Single
ClosestUnder = DMax ("field_1","YourTableOrQuery", "field_1 >= " & ValueIn)
ClosestOver = DMin ("field_1","YourTableOrQuery", "field_1 <= " & ValueIn)
If ClosestOver - ValueIn > ValueIn - ClosestUnder Then
   ReturnClosestValue = ClosestUnder
Else
   ReturnClosestValue = ClosestOver
End IF
End Function

ReturnClosestValue (3.77)
NatchiketCommented:
SELECT TOP 1 Field_1  FROM table ORDER BY Abs(field_1-3.77)

The above will give more than one record if there is more than one value with excatly the same closeness to field_1
so
SELECT TOP 1 * FROM (SELECT TOP 1 Field_1  FROM table ORDER BY Abs(field_1-3.77))

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft Access

From novice to tech pro — start learning today.