Return percentage match when perform an SQL Query

Posted on 2000-02-18
Last Modified: 2008-10-04
Dear Expert
How do i do an SQL query that will search through a database and return all data that match at least one of the variables being search. The query must also sort the data into order from 100% match (all variables) down. ie similary to what most web sites use when searching databases.
Question by:bornfree
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
  • 2
  • +3
LVL 12

Expert Comment

ID: 2534563
How would you like the percentages to be calucated? According to how many times the word(s) appear in the text or just based on how many of the that match. The first one will most likely force you to make a "statistics" table that counts the words per article so that you can use this in the calculations. If you are to count them "on the fly", your query will be slooooooow.

Author Comment

ID: 2534607
I will not be searching a text document. Assume the main database consists a number of fields, each field contains specific info. if i would like to do a search and reflect the percentage of matches vs total i have searched on.

ie lets say i have a database of employees, with fields for gender, height, hair colour etc. I would then like to do a search for male, blonde hair and brown eyes. I would therefore like my query to return in order of 100%, 67%, 33%

hpe this makes more sence.
LVL 12

Expert Comment

ID: 2534655
SELECT Match1: iif([Gender]='Male',1,0), Match2: iif([Hair Color]='Blonde',1,0), Match3: Iif([Eye Color]='Brown',1,0) FROM TableName

Now you can do the calculation on your form/report  =([Mathc1]+[Match2]+[Match3])/3

or change the query

SELECT Match1: iif([Gender]='Male',1,0), Match2: iif([Hair Color]='Blonde',1,0), Match3: Iif([Eye Color]='Brown',1,0), FoundPercentage: [Match1]+[Match2]+[Match3] FROM TableName

If this is not valid (and I am not sure if it is, then try this:

SELECT Match1: iif([Gender]='Male',1,0), Match2: iif([Hair Color]='Blonde',1,0), Match3: Iif([Eye Color]='Brown',1,0), FoundPercentage: iif([Gender]='Male',1,0) + iif([Hair Color]='Blonde',1,0) + Iif([Eye Color]='Brown',1,0) FROM TableName
Use Case: Protecting a Hybrid Cloud Infrastructure

Microsoft Azure is rapidly becoming the norm in dynamic IT environments. This document describes the challenges that organizations face when protecting data in a hybrid cloud IT environment and presents a use case to demonstrate how Acronis Backup protects all data.


Expert Comment

ID: 2534681
Hi bornfree.
You can use DCount aggregate function:

Dim intTotalEmployees
Dim intMale as Integer
Dim intMaleBlonde as Integer
Dim intMaleBlondeAndBrownEyes as Integer

intTotalEmployees = Dcount("EmpId", "Employees")
intMale = DCount("EmpId", "Employees", "[Gender]='male'")
intMaleBlonde = DCount("EmpId", "Employees", "[Gender]='male' And [Hair Color] = 'Blonde'")
intMaleBlondeAndBrownEyes = ("EmpId", "Employees", "[Gender]='male' And [Hair Color] = 'Blonde' And [Eyes Color] = 'Brown'")

Debug.Print "Total - " & intTotalEmployees & " (100%)"
Debug.Print "Males - " & intMale & " (" & Int(intMale /intTotalEmployees *100) & "%)"
intTotalEmployees & " (100%)"
Debug.Print "Blonde - " & intMaleBlonde & " (" & Int(intMaleBlonde /intMale *100) & "%)"
Debug.Print "Brown Eyes - " & intMaleBlondeAndBrownEyes & " (" & Int(intMaleBlondeAndBrownEyes /intMaleBlonde *100) & "%)"

LVL 12

Expert Comment

ID: 2534903
Dedushka: The task here seems to be to list all the records that match and then sort them according to the hit-percentage. Using the DCounts would be nice if you wondered about the total percentages.
LVL 10

Accepted Solution

paasky earned 150 total points
ID: 2535282
Hello bornfree,

You could try something like this:

((E.HairColor=[Hair color: ])*-1 +
 (E.Gender=[Gender: ])*-1 +
 (E.EyeColor=[Eye color: ])*-1
) / 3 * 100 AS [Match Percentage]

You can add as many criteria you need and divide the number with number of criterias.


Expert Comment

ID: 2535603
Just a variation on the above comments.  This selects the match fields and calculates the percent match in one field (MatchPct) and then orders the records by that percent descending:

SELECT Name, Gender, HairColor, EyeColor, IIf([Gender] = "Male", 1/3*100,0) + IIf([HairColor] = "Blonde", 1/3*100,0) + IIf([EyeColor] = "Blue", 1/3*100,0) as MatchPct FROM Table WHERE Gender = "Male" OR HairColor = "Blonde" OR Eyecolor = "Blue" ORDER BY MatchPct desc;

To use it just change the table and field names to the ones your DB uses and change the "1/3*100" calculation to however many criteria you use.  For instance, if you used 5 criteria, then the calculation would be "1/5*100".
HTH, good luck as usual...

Expert Comment

ID: 2535633
BTW, bornfree, tha above will select all males, all blondes (male *and* female), and all blue eyes (male *and* female).  I hope that's what you had in mind?
good luck as usual...
LVL 30

Expert Comment

ID: 2536407

' Try this query.  It references a function as bellow.

SELECT tbl.fld1, tbl.fld2, tbl.fld3, percent_match([fld1],"male",[fld2],"blonde hair",[fld3],"brown eyes") AS myMatch
FROM tbl
ORDER BY percent_match([fld1], "male",[fld2], "blonde hair", [fld3], "brown eyes") DESC;

' here is the function:

Public Function percent_match(f1, c1, f2, c2, f3, c3 As String) As Integer
' f stands for field, c stands for criteria
    Dim myMatch As Integer
    myMatch = 0
    If f1 = c1 Then
        myMatch = myMatch + 1
    End If
    If f2 = c2 Then
        myMatch = myMatch + 1
    End If
    If f3 = c3 Then
        myMatch = myMatch + 1
    End If
    Select Case myMatch
        Case 1
            percent_match = 33
        Case 2
            percent_match = 66
        Case 3
            percent_match = 100
        Case Else
            percent_match = 0
    End Select
End Function

' you may use constants instead of the numbers.

Author Comment

ID: 2546493
Why do you multiply the selection by -1 for each search variable?
LVL 10

Expert Comment

ID: 2548083

True = -1, and if we want positive percent value, we must multiply condition return value by -1 (-1 * -1 = 1).

You're right that it's not necessary to do the multiplying for all values - this should do the same trick:

(((E.HairColor=[Hair color: ]) +
 (E.Gender=[Gender: ]) +
 (E.EyeColor=[Eye color: ])) * -1
) / 3 * 100 AS [Match Percentage]


Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

As tax season makes its return, so does the increase in cyber crime and tax refund phishing that comes with it
In Part II of this series, I will discuss how to identify all open instances of Excel and enumerate the workbooks, spreadsheets, and named ranges within each of those instances.
Using Microsoft Access, learn some simple rules for how to construct tables in a relational database. Split up all multi-value fields into single values: Split up fields that belong to other things into separate tables: Make sure that all record…
In Microsoft Access, learn how to use Dlookup and other domain aggregate functions and one method of specifying a string value within a string. Specify the first argument, which is the expression to be returned: Specify the second argument, which …

749 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question