2014-02-06 24 views
0

我有一个数据库,有时会存储重复的行,但是重复的数据不是明确的,例如,以下两点的值将是一个重复:SQL获取具有相似列值的行

G12345 & G1234 --> because they are very similar 
(a string comparison shows that the characters match 83.3%). 

我需要一些帮助编写SQL查询,将检索非常相似发送作为查询的一部分,例如一个字符串值超过50%的字符匹配。

有人可以帮忙吗?我有一个C#方法如下,但不太清楚如何在SQL中完成此操作:

static double StringCompare(string a, string b) 
{ 
    if (a == b) //Same string, no iteration needed. 
    return 100; 
    if ((a.Length == 0) || (b.Length == 0)) //One is empty, second is not 
    { 
    return 0; 
    } 
    var maxLen = a.Length > b.Length ? a.Length : b.Length; 
    var minLen = a.Length < b.Length ? a.Length : b.Length; 
    var sameCharAtIndex = 0; 
    for (var i = 0; i < minLen; i++) //Compare char by char 
    { 
    if (a[i] == b[i]) 
    { 
     sameCharAtIndex++; 
    } 
    } 
    return sameCharAtIndex/maxLen * 100; 
} 

在此先感谢。

回答

0

不知道如果你试图使用SQL-Server或MySQL,但是您可以创建和SQL-Server中使用下列功能:

create function StringCompare 
    (@A nvarchar(200), 
    @B nvarchar(200) 
    ) 
returns float 
as 
begin 
    if (
     @A = @B 
     or (@A is null and @B is null) 
     ) 
    begin 
     return 100.0 
    end 

    if (
     ((@A is null or len(@A) = 0) and (@B is not null and len(@B) > 0)) 
     or ((@B is null or len(@B) = 0) and (@A is not null and len(@A) > 0)) 
     ) 
    begin 
     return 0.0 
    end 

    declare @maxLen int 
    set @maxLen = case when len(@A) > len(@B) then len(@A) else len(@B) end 

    declare @minLen int 
    set @minLen = case when len(@A) < len(@B) then len(@A) else len(@B) end 

    declare @sameCharAtIndex int 
    set @sameCharAtIndex = 0 

    declare @count int 
    set @count = 1 

    while (@count <= @minLen) 
    begin 
     if (SUBSTRING(@A, @count, 1) = substring(@B, @count, 1)) 
     begin 
      set @sameCharAtIndex = @sameCharAtIndex + 1 
     end 

     set @count = @count + 1 
    end 

    return cast(@sameCharAtIndex as float)/cast(@maxLen as float) * 100.0 

end 

它可以在任何语句中使用如下:

select dbo.StringCompare('test', 'test'), dbo.StringCompare('nope', 'test'), dbo.StringCompare('partial', 'parsomethingelse') 

请注意,在许多记录上运行的sql中有这样一个循环可能效率低下。你可能想考虑你是否真的必须在SQL中完成它。

+0

感谢这非常有用我会尝试一下。搜索将仅限于少数记录。 – Tommy

0

使用Mysql Like Operator而不是在服务层进行操作。

SELECT * FROM table WHERE column LIKE 'G12___' or 'G12%'. 

SELECT * FROM table WHERE column LIKE '%input string as parameter%'. 

的“_”通配符LIKE谓词装置“的任何字符之一,”等同于“”在正则表达式中。

参见this以供参考。

+0

来吧,这是怎么缩放的。 'G12345'只是一个例子 –

+0

是的,这是正确的提供的数据只是一个例子,我正在寻找的东西,可以正确缩放和字符可能不连续。 – Tommy

+0

@ user2310289:仅供参考,您可以将它作为参数传递给sql。这就是它的规模。 –

相关问题