2017-04-06 124 views
4

我有一個過程,在我提交數據到數據庫之前,我必須檢查數據庫中是否已經存在數據。如果它找到相似性,我想顯示它的相似百分比。 我有一個查詢,如:如何在SQL Server中查詢相似度百分比?

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

我要讓如果只是名稱的名字,我輸入和存在於數據庫中的名稱相似,它顯示了類似的25%。如果只有名字和生日,那麼50%。如果全部相似,那麼100%。你知不知道怎麼?

回答

4

假設匹配百分比是基於匹配性能的數量,你可以使用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 
+0

我已經嘗試過了,但match_percentage顯示所有空值 – hendraspt

+0

@hendraspt - 哎呀。錯過了'else'部分。現在更新。請再試一次? – GurV