如何删除在SQL Server中交换了名字/姓氏的重复用户

时间:2018-11-24 13:13:45

标签: sql duplicates

考虑一下,我有一个类似下面的表格:

Firstname : LastName
Ajay      : Sharma
Sharma    : Ajay
Gopi      : Nair
Nair      : Gopi
Vikram    : Roy
Anil      : Patel
Patel     : Anil

enter image description here

我希望得到的输出为

Firstname : LastName

Ajay      : Sharma
Gopi      : Nair
Vikram    : Roy
Anil      : Patel

enter image description here

3 个答案:

答案 0 :(得分:0)

  SELECT FIRSTNAME,LASTNAME FROM TABLE WHERE 
  LASTNAME, FIRSTNAME NOT IN (SELECT 
  FIRSTNAME,LASTNAME FROM TABLE) ;

答案 1 :(得分:0)

您可以在UNION中与所有子查询一起返回重复项的子查询中使用删除操作

delete m 
from my_table m
inner 
     (select t.firtname, t.lastname
      from 
          (select firtname, lastname
           from my_table 

           union all

           select lastname, firstname 
           from my_table) t 
      group by 
          t.firtname, t.lastname
      having 
          count(*) > 1) t2 on t2.lastname = m.firstname 
                           and t2.firstname = m.lastname

答案 2 :(得分:0)

没有通常的名字和/或姓氏列表,就不可能保持“看起来”像名字一样。因此,您只能求助于一对。

我会去

select t.firstname, t.lastname
from t
where t.firstname <= t.lastname
union all
select t.lastname, t.firstname
from t
where t.firstname > t.lastname and
      not exists (select 1
                  from t t2
                  where t2.firstname = t.lastname and
                        t2.lastname = t.firstname
                 );

这将保留firstname小于或等于lastname的所有行。然后在不存在反转的地方保留反转对。

如果您实际上要删除行:

delete from t
    where t.lastname > t.firstname and
          exists (select 1
                  from t t2
                  where t2.firstname = t.lastname and
                        t2.lastname = t.firstname
                 );