473,419 Members | 1,593 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,419 software developers and data experts.

How do I find the record that is closest to a given number?

Seth Schrock
2,965 Expert 2GB
I'm trying to simplify a very complex problem, so it is possible that I might leave out a few details, but I will try not to.

Basically, I have a table which has a number field (among others) that have a variable distance between the numbers. For example, the table might hold the following numbers:
Expand|Select|Wrap|Line Numbers
  1. 98.891
  2. 100.664
  3. 101.527
  4. 102.344
  5. 103.135
I need to be able to type a number in a form and find the record whose number is closest to the one that I entered. For example if I enter 101.4, then it will find the third record. If I enter 100.7, it would find the second record. I have come up with a very complicated process of using two recordsets and looping through the table with the first recordset starting on the first record and the second recordset starting on the second and then do a .MoveNext on each at the same time and then testing if the value in recordset 1 is less than or equal to the value and recordset 2 is greater than or equal to the value so that I could find the two records that the value is between and then subtract the lower amount from the given amount and the given amount from the higher amount and compare the two results to see which one is closer. Again, this seems very complicated. I just hope someone can either come up with a better idea or just confirm that my idea is the only way to go.

Hopefully I made my question clear.
May 8 '13 #1

✓ answered by Rabbit

Try something like this:
Expand|Select|Wrap|Line Numbers
  1. SELECT *
  2. FROM tableName
  3. WHERE ABS(# - fieldName) = (
  4.    SELECT MIN(ABS(# - fieldName))
  5.    FROM tableName
  6. )
Note that this can return multiple records if they are equidistant from the target.

5 10180
Rabbit
12,516 Expert Mod 8TB
Try something like this:
Expand|Select|Wrap|Line Numbers
  1. SELECT *
  2. FROM tableName
  3. WHERE ABS(# - fieldName) = (
  4.    SELECT MIN(ABS(# - fieldName))
  5.    FROM tableName
  6. )
Note that this can return multiple records if they are equidistant from the target.
May 8 '13 #2
ADezii
8,834 Expert 8TB
Assuming a Table Name of Table1, a Field Name of [Field1] containing the actual Values for comparison, and a Field named txtNumber on a Form that contains the Test Value, then the following Code will:
  1. Create a Query consisting of the [Field1] Value along with the Minimal Variance between it and the actual Test Value.
  2. Display the Query Results.
  3. Code:
    Expand|Select|Wrap|Line Numbers
    1. On Error Resume Next
    2. Dim strSQL As String
    3. Dim qdf As DAO.QueryDef
    4. Const conQueryName As String = "Test Query"
    5.  
    6. CurrentDb.QueryDefs.Delete conQueryName
    7.  
    8. strSQL = "SELECT TOP 1 Table1.Field1, Abs(" & CSng(Me![txtNumber]) & "-[Field1]) AS Variance " & _
    9.          "FROM Table1 ORDER BY Abs(" & CSng(Me![txtNumber]) & "-[Field1]);"
    10.  
    11. Set qdf = CurrentDb.CreateQueryDef(conQueryName, strSQL)
    12.  
    13. DoCmd.OpenQuery conQueryName
  4. Results for Test Value of 100.7:
    Expand|Select|Wrap|Line Numbers
    1. Field1    Variance
    2. 100.664    0.036
    3.  
  5. Results for Test Value of 101.4:
    Expand|Select|Wrap|Line Numbers
    1. Field1    Variance
    2. 101.527    0.127
    3.  
  6. The SQL, along with the Results, should you wish to include the Test Value in the Text Box is:
    Expand|Select|Wrap|Line Numbers
    1. strSQL = "SELECT TOP 1 Table1.Field1, Abs(" & CSng(Me![txtNumber]) & "-[Field1]) AS Variance, " & _
    2.           Me![txtNumber] & " FROM Table1 ORDER BY Abs(" & CSng(Me![txtNumber]) & "-[Field1]);"
    Expand|Select|Wrap|Line Numbers
    1. 'Results for a Test Value of 101.4 in Me![txtNumber]
    2. Field1      Variance    Expr1002
    3. 101.527     0.127       101.4
P.S. - Any questions, please feel free to ask.
May 8 '13 #3
Seth Schrock
2,965 Expert 2GB
Thank-you so much to both of you. I will try it out as soon as I can. I will be spending most of tomorrow tearing out old equipment, but hopefully I will get it done quickly so that I can try your solutions. I'm glad that there is a solution that is simpler than mine. I wasn't looking forward to putting my idea into code.
May 9 '13 #4
NeoPa
32,556 Expert Mod 16PB
In technical terms, you simply find the absolute (signless) value after subtracting your value from the value in each record of the table. The record which reflects the smallest of these (in magnitude) is the one you're looking for.
May 10 '13 #5
Seth Schrock
2,965 Expert 2GB
Thanks Rabbit and ADezii for your solutions and to NeoPa for the explanation. I think that my final solution will be a combination of the two solutions, but that was so much simpler than my idea. I will choose Rabbit's as best answer as it is the simplest, but I will probably end up using a VBA implementation of the Rabbit's SQL so ADezii's code is certainly beneficial.

Thanks again.
May 13 '13 #6

Sign in to post your reply or Sign up for a free account.

Similar topics

3
by: Randy | last post by:
I have been able to set up a Find Record Button on my switchboard to take me to a form with the correct case number by using a parameter query and macro. When I try to run the Find Record button...
13
by: Kishor | last post by:
Hi Friends Please help me to write a C program to find the 5th (fifth) root of a given number. Ex:(1) Input : 32 Output : 5th root of 32 is 2 Ex:(1) Input : 243 Output : 5th root of 243 is...
7
by: gjoneshtfc | last post by:
Hello I want to search my database for a vehicle registration number but before i can search using the Find Record button i created i have to click in the registration field so that it is that...
11
by: gchiazx | last post by:
Hi, can someone send me the algorithm for finding the products of prime numbers from a given number? Thank You Gary.
1
by: psbasha | last post by:
Hi, How to find the number of digits from a given number?. For example num = 23456 The number of digits are 5 num = 2311150
5
by: jm.suresh | last post by:
Hi I have three objects, all of them are instances of classes derived from a base class. Now, given one of the instance, I want to find the closest relative of the other two. How can I do this? ...
3
by: betterdayz | last post by:
hi...im trying to design the "find record" command whereby the user enters an ID Number and than clicks ok and the database does a search for that particular ID...the wizard command uses find and...
7
by: GraemeC | last post by:
I have a form (single record form) that loads records from a query that are sorted date order as the records are viewed in date order. Some dates are in the past and some are in the future. Currently...
15
by: shivpratap | last post by:
I m solving a problem to find the sum of divisors of a given number(the number is a large one),...i hv written the code bt it's exceding the time limit...hw can i reduce the time in such cases...pls...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.