How to make a similarity percentage query in SQL Server?

I have a process that before sending data to the database must check if the data exists in the database or not. And if he found a similarity, I want to show a percentage similarity. I have a query like:

SELECT [NAME]
      ,[IDENTITY_NUMBER]
      ,[BIRTHDATE]
      ,[SEX]
FROM [USER]
WHERE [NAME] = @NAME
OR [IDENTITY_NUMBER] = @IDENTITY_NUMBER
OR [BIRTHDATE] = @BIRTHDATE
OR [SEX] = @SEX

I want to do it, if only the name matches the name I entered and the name that exists in the database, it looks like 25%. if only name and date of birth, then 50%. if everything is similar, then 100%. Do you know how?

+4
source share
1 answer

Assuming that the percent match is based on the number of matching properties, you can use case:

select [NAME],
    [IDENTITY_NUMBER],
    [BIRTHDATE],
    [SEX],
    case when [NAME] = @NAME then 25 else 0 end
    + case when [IDENTITY_NUMBER] = @IDENTITY_NUMBER then 25 else 0 end
    + case when [BIRTHDATE] = @BIRTHDATE then 25 else 0 end
    + case when [SEX] = @SEX then 25 else 0 end as match_percentage
from [USER]
where [NAME] = @NAME
    or [IDENTITY_NUMBER] = @IDENTITY_NUMBER
    or [BIRTHDATE] = @BIRTHDATE
    or [SEX] = @SEX
+4

Source: https://habr.com/ru/post/1674154/


All Articles