2012-10-28 107 views
5

我有一個與SQL有關的問題。SQL模式匹配

我想匹配兩個領域的相似之處,並返回相似的百分比。

例如,如果我有一個名爲doc場,其中包含以下

​​

,並在另一個領域我有類似

My first assignment in SQL 

我想知道我怎麼能檢查的相似之處兩者之間又有多少百分比回報。

我做了一些研究,想要第二個意見加我從來沒有要求的源代碼。我看了Soundex(),Difference(),使用Levenshtein距離算法的模糊字符串匹配。

+3

提示:查找到'海明distance'和類似串相似性的算法 –

+1

我做了一些研究,並希望第二意見加上我從來沒有要求的源代碼。我看了Soundex(),Difference(), 使用Levenshtein距離算法的模糊字符串匹配。謝謝你的提示 – user1781162

回答

5

你沒有說你正在使用哪個版本的Oracle。這個例子基於11g版本。 您可以使用utl_match包的edit_distance函數確定需要更改多少個字符才能將一個字符串轉換爲另一個字符串。 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正確地指出,這是更易於使用utl_matchedit_distance_similarity功能。

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 
+0

謝謝!我正在使用Oracle 11G。我沒有期待任何代碼,所以謝謝! – user1781162

+2

+1你可以用'utl_match.edit_distance_similarity(col1,col2)'來簡化它。 –