我有一个与 SQL 相关的问题。
我想匹配两个字段的相似性,并返回有关相似程度的百分比。
例如,如果我有一个名为 doc 的字段,其中包含以下内容
This is my first assignment in SQL
在另一个领域,我有类似的东西
My first assignment in SQL
我想知道如何检查两者之间的相似性并返回多少百分比。
我做了一些研究,想要第二个意见,而且我从未要求过源代码。我看过 Soundex()、Difference()、使用 Levenshtein 距离算法的模糊字符串匹配。
最佳答案
您没有说明您使用的是哪个版本的 Oracle。此示例基于 11g 版本。
您可以使用 edit_distance
utl_match 的功能包以确定您需要更改多少个字符才能将一个字符串转换为另一个字符串。 greatest函数返回传入参数列表中的最大值。下面是一个例子:
-- sample of data
with t1(col1, col2) as(
select 'This is my first assignment in SQL', 'My first assignment in SQL ' from dual
)
-- the query
select trunc(((greatest(length(col1), length(col2)) -
(utl_match.edit_distance(col2, col1))) * 100) /
greatest(length(col1), length(col2)), 2) as "%"
from t1
结果:
%
----------
70.58
附录
正如@jonearles 正确指出的那样,使用
edit_distance_similarity
要简单得多。 utl_match
的功能包裹。 with t1(col1, col2) as(
select 'This is my first assignment in SQL', 'My first assignment in SQL ' from dual
)
select utl_match.edit_distance_similarity(col1, col2) as "%"
from t1
;
结果:
%
----------
71
关于SQL模式匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13111249/