根据某条记录搜索相似的记录,假设表如下:sid   f1   f2   f3   f4 
1     a    1    R   1.0  
2     t    5    E   5.0
3     c    1    R   1.0
4     t    11   E   2.0
5     a    1    R   1.0
6     u    5    E   5.0
7     t    5    E   5.0    比如,搜索和记录1相似的记录,那么返回结果应为:sid   f1   f2   f3   f4 
1     a    1    R   1.0  (参考记录)
5     a    1    R   1.0  (完全相同)
3     c    1    R   1.0  (非常相似,除sid外只有1个偏差)    其中偏差值(或者叫相似度)允许设定,范围0~<字段数,如果为0那么只搜索出完全相同的记录。    再比如,搜索和记录7偏差值为2的相似记录,那么返回结果应为:sid   f1   f2   f3   f4 
7     t    5    E   5.0  (参考记录)
2     t    5    E   5.0  (完全相同)
6     u    5    E   5.0  (偏差值为1)
4     t    11   E   2.0  (偏差值为2)    另外,返回结果应按照偏差值升序排序,即越相似的越靠前。    请教大家,先谢谢了。

解决方案 »

  1.   

    declare @sid int
    set @sid=1                      --sid可以是参数declare @偏差值 int
    set @偏差值=1                   --偏差值可以是参数select a.* from tablename a,tablename b
    where b.sid=@sid
    and case when a.f1=b.f1 then 0 else 1 end+ 
        case when a.f2=b.f2 then 0 else 1 end+
        case when a.f3=b.f3 then 0 else 1 end+
        case when a.f4=b.f4 then 0 else 1 end
        <=1
      

  2.   

    declare @sid int
    set @sid=1                      --sid可以是参数declare @偏差值 int
    set @偏差值=1                   --偏差值可以是参数select a.* from tablename a,tablename b
    where b.sid=@sid
    and case when a.f1=b.f1 then 0 else 1 end+ 
        case when a.f2=b.f2 then 0 else 1 end+
        case when a.f3=b.f3 then 0 else 1 end+
        case when a.f4=b.f4 then 0 else 1 end
        <=@偏差值
      

  3.   

    加排序declare @sid int
    set @sid=1                      --sid可以是参数declare @偏差值 int
    set @偏差值=1                   --偏差值可以是参数select a.* from tablename a,tablename b
    where b.sid=@sid
    and case when a.f1=b.f1 then 0 else 1 end+ 
        case when a.f2=b.f2 then 0 else 1 end+
        case when a.f3=b.f3 then 0 else 1 end+
        case when a.f4=b.f4 then 0 else 1 end
        <=@偏差值
    order by 
        case when a.sid=@sid then 0 else 1 end+ 
        case when a.f1=b.f1 then 0 else 1 end+ 
        case when a.f2=b.f2 then 0 else 1 end+
        case when a.f3=b.f3 then 0 else 1 end+
        case when a.f4=b.f4 then 0 else 1 end