在多列t-sql中查找重复项

时间:2017-03-06 14:32:26

标签: sql-server tsql sql-server-2008-r2

我有以下表格

col_1   col_2   col_3   col_4   

1       2       3       1

4       6       1       2

7       5       8       3

0       7       9       4

例如,在上表中,第一行(第一列)中的值“1”在第二行(第三列)中重复。所以我的结果中不需要第二行。同样地,我想在现有表中识别重复的行,并且我必须仅显示下面的预期结果中的行。如何使用t-sql实现这一目标?

注意:Col_4是唯一标识每一行的列。此列不应包含在重复评估中,但应用于删除重复行,如下所示(col_4的升序)。

我的预期结果:

col_1   col_2   col_3  

1       2       3       

7       5       8

3 个答案:

答案 0 :(得分:0)

select col1, col2, col3 
from table t1 
where not exists ( select 1 
                   from table t2 
                   where t1.col4 < t2.col4 
                   and (    t2.col1 = t1.col1 
                         or t2.col2 = t1.col1
                         or t2.col3 = t1.col1 
                       )
                 )

答案 1 :(得分:0)

  

尝试下面的解决方案。复制并粘贴到sql studio。

 create table cols
 (
 col1 smallint,
 col2 smallint,
 col3 smallint,
  col4 INT IDENTITY(1,1) NOT NULL
 );


 insert into cols
 values(1,2,3),(4,6,1),(7,5,8),(0,7,9),(11,12,13),(17,15,16),(10,17,20),(11,2,3)


select *  from cols

select * from cols where col4 in (
 select t2.col4 from cols t1
  inner join (
   select col1,col2,col3,col4 from cols 
   ) t2 on
    (t1.col1 = t2.col1 or t1.col1 = t2.col2 or t1.col1 = t2.col3 or
    t1.col2 = t2.col1 or t1.col2 = t2.col2 or t1.col2 = t2.col3 or
    t1.col3 = t2.col1 or t1.col3 = t2.col2 or t1.col3 = t2.col3 )
        and t1.col4 > t2.col4
 ) 



 drop table cols

答案 2 :(得分:-1)

在同一张桌子上进行内部联接,对所有感兴趣的列进行比较并检查唯一ID,以确保您不会最终加入自己的记录

select mytable a
inner join mytable b on (a.col1 = b.col1 or a.col1 = b.col2 or a.col1 = bcol3 or a.col2 = b.col1 or ...etc...) and a.id != b.id

那应该会给你一份重复的清单。我还没有对它进行过测试,但我相信这应该可行。

修改 - 我已对上述内容进行了测试,我可以确认其有效

相关问题