Solved

Return percentage match when perform an SQL Query

Posted on 2000-02-18
11
1,195 Views
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.
0
Comment
Question by:bornfree
  • 3
  • 2
  • 2
  • +3
11 Comments
 
LVL 12

Expert Comment

by:Trygve
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.
0
 

Author Comment

by:bornfree
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.
0
 
LVL 12

Expert Comment

by:Trygve
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
0
Back Up Your Microsoft Windows Server®

Back up all your Microsoft Windows Server – on-premises, in remote locations, in private and hybrid clouds. Your entire Windows Server will be backed up in one easy step with patented, block-level disk imaging. We achieve RTOs (recovery time objectives) as low as 15 seconds.

 
LVL 7

Expert Comment

by:Dedushka
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) & "%)"

Regards,
Dedushka
0
 
LVL 12

Expert Comment

by:Trygve
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.
0
 
LVL 10

Accepted Solution

by:
paasky earned 150 total points
ID: 2535282
Hello bornfree,

You could try something like this:

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

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

Regards,
Paasky
0
 
LVL 3

Expert Comment

by:tomk120999
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...
0
 
LVL 3

Expert Comment

by:tomk120999
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...
0
 
LVL 30

Expert Comment

by:hnasr
ID: 2536407
'bornfree,

' 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.
0
 

Author Comment

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

Expert Comment

by:paasky
ID: 2548083
bornfree:

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:

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

Regards,
Paasky
0

Featured Post

Ransomware-A Revenue Bonanza for Service Providers

Ransomware – malware that gets on your customers’ computers, encrypts their data, and extorts a hefty ransom for the decryption keys – is a surging new threat.  The purpose of this eBook is to educate the reader about ransomware attacks.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Need to Populate a MS Access Table via VBA Code 3 31
Dlookup MSACCESS 5 25
Turn off MS Access Default=0 for Numerics 6 26
SQL Group on First occurrence 9 25
Experts-Exchange is a great place to come for help with solutions for your database issues, and many problems are resolved within minutes of being posted.  Others take a little more time and effort and often providing a sample database is very helpf…
Describes a method of obtaining an object variable to an already running instance of Microsoft Access so that it can be controlled via automation.
Familiarize people with the process of utilizing SQL Server stored procedures from within Microsoft Access. Microsoft Access is a very powerful client/server development tool. One of the SQL Server objects that you can interact with from within Micr…
Basics of query design. Shows you how to construct a simple query by adding tables, perform joins, defining output columns, perform sorting, and apply criteria.

810 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