我有两列可能包含类似数据,我正试图弄清楚如何比较两者的相似之处。
TABLE:
PatientID | InsurnaceCompany1 | InsuranceCompany2
111111111 | Medicaid | Medicaid - Part D
222222222 | Medicaid - ABC Co | Medicaid
333333333 | Medicaid - ABC Co | Medicaid - Part D
444444444 | MVP Insurance | MVP
555555555 | Medicare | Medicaid
666666666 | Medicaid | MVP
777777777 | Private - MVP | MVP Option
问题是, 如何比较两列以了解它们是否相似。
结果应该是这样的:
PatientID | InsurnaceCompany1 | InsuranceCompany2 | Result
111111111 | Medicaid | Medicaid - Part D | TRUE
222222222 | Medicaid - ABC Co | Medicaid | TRUE
333333333 | Medicaid - ABC Co | Medicaid - Part D | TRUE
444444444 | MVP Insurance | MVP | TRUE
555555555 | Medicare | Medicaid | FALSE
666666666 | Medicaid | MVP | FALSE
777777777 | Private - MVP | MVP Option | TRUE
我可以使用case语句检查以下几个选项,如:
case
when InsuranceCompany1 like '%' + InsuranceCompany2 + '%' then 'TRUE'
when InsuranceCompany2 like '%' + InsuranceCompany1 + '%' then 'TRUE'
else 'FALSE'
end AS Result
但上述PatientID 333333333和777777777的测试失败。
为了澄清,我将如下定义“类似”:如果它们各自包含相同的单词,则两个术语相似。即使这个词是通用的(例如“保险”),这也适用。所以“保险公司B”类似于“保险公司A”,原因有两个:“保险”和“公司”。
答案 0 :(得分:0)
我认为你的问题中暗含了许多特定于领域的知识(究竟是什么构成了“相似”的名字),而且你无法通过一般目的的比较来解决这个问题。您最好的选择可能是在您的查询中枚举您的特定要求,这样您就可以准确控制您所获得的内容:
select
*
from
patients
where
InsuranceCompany1 like concat('%', InsuranceCompany2, '%') or
InsuranceCompany2 like concat('%', InsuranceCompany1, '%') or
(InsuranceCompany1 like '%medicaid%' and InsuranceCompany2 like '%medicaid%') or
(InsuranceCompany1 like '%medicare%' and InsuranceCompany2 like '%medicare%') or
(InsuranceCompany1 like '%mvp%' and InsuranceCompany2 like '%mvp%') or
...etc...
答案 1 :(得分:-2)
修改
DECLARE @t TABLE (PatientID INT, InsurnaceCompany1 NVARCHAR(50), InsuranceCompany2 NVARCHAR(50))
INSERT INTO @t
VALUES
(111111111,'Medicaid' ,'Medicaid - Part D'),
(222222222,'Medicaid - ABC Co' ,'Medicaid'),
(333333333,'Medicaid - ABC Co' ,'Medicaid - Part D'),
(444444444,'MVP Insurance' ,'MVP'),
(555555555,'Medicare' ,'Medicaid'),
(666666666,'Medicaid' ,'MVP'),
(777777777,'Private - MVP' ,'MVP Option')
SELECT PatientID, InsurnaceCompany1, InsuranceCompany2 ,
CASE WHEN LEFT(InsurnaceCompany1,CASE WHEN CHARINDEX(' ', InsurnaceCompany1) = 0
THEN LEN(InsurnaceCompany1) ELSE CHARINDEX(' ', InsurnaceCompany1) END )
= LEFT(InsuranceCompany2,CASE WHEN CHARINDEX(' ', InsuranceCompany2) = 0
THEN LEN(InsuranceCompany2) ELSE CHARINDEX(' ', InsuranceCompany2) END )
THEN 'TRUE' ELSE 'FALSE' END AS RESULT
FROM @t
结果集
PatientID InsurnaceCompany1 InsuranceCompany2 RESULT
111111111 Medicaid Medicaid - Part D TRUE
222222222 Medicaid - ABC Co Medicaid TRUE
333333333 Medicaid - ABC Co Medicaid - Part D TRUE
444444444 MVP Insurance MVP TRUE
555555555 Medicare Medicaid FALSE
666666666 Medicaid MVP FALSE
777777777 Private - MVP MVP Option FALSE