【问题标题】:Remove Duplicates from my SQL Server table从我的 SQL Server 表中删除重复项
【发布时间】:2016-12-15 04:18:37
【问题描述】:

我有一张包含以下数据的表格。

Col1    Col2
 A       B
 B       A
 C       D
 D       C
 E       F
 F       E

如果多行中的(col1 and Col2)和(col2 and Col1)值相同,则认为它们是重复的。在上面的例子中,第1行和第2行之间的Col1和Col2相同,它们被认为是作为重复。我们只需要其中的 1 行。

所以上面例子的输出是,

Col1   Col2
 A      B
 C      D 
 E      F

Col1   Col2
 B      A
 D      C 
 F      E

请帮帮我。

谢谢..

【问题讨论】:

    标签: sql sql-server duplicates


    【解决方案1】:

    试试这个:

    rextester:http://rextester.com/XCYU52032

    create table tb (col1 char(1), col2 char(1))
    insert into tb (col1, col2) values
     ('a','b')
    ,('b','a')
    ,('c','d')
    ,('d','c')
    ,('e','f')
    ,('f','e');
    
    with cte as (
        select col1, col2, rn = row_number() over(order by col1)
        from tb
        )
    
    /* 
        select x.* 
          from cte as x
          where not exists (
            select 1 
              from cte as y 
              where y.col2 = x.col1
                and x.rn>y.rn  -- returns col1 in ('a','c','e')
                --and x.rn<y.rn  -- returns col1 in ('b','d','f')
            )
    
    --*/
    
        delete x 
          from cte as x
          where not exists (
            select 1 
              from cte as y 
              where y.col2 = x.col1
                --and x.rn>y.rn  -- returns col1 in ('a','c','e')
                and x.rn<y.rn  -- returns col1 in ('b','d','f')
            )
    
    select * from tb
    

    【讨论】:

      【解决方案2】:

      试试

      delete from myTable t1
      where col1 > col2 and exists (select 1 
                                  from myTable t2 
                                  where t2.col1 = t1.col2 and t2.col2 = t1.col1);
      

      【讨论】:

      • 这行得通。您的代码中有一个小的更正。 myTable 别名在外部查询中应为“t1”。不是“不”。非常感谢塞尔格...
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-13
      • 2020-07-07
      • 2014-07-21
      • 1970-01-01
      • 2021-02-05
      • 1970-01-01
      相关资源
      最近更新 更多