从我的SQL Server表中删除重复项
我有一个包含以下数据的表格从我的SQL Server表中删除重复项,sql,sql-server,duplicates,Sql,Sql Server,Duplicates,我有一个包含以下数据的表格 Col1 Col2 A B B A C D D C E F F E 如果多行中的col1和Col2以及Col2和col1值相同,则认为它们是重复的。在上例中,第1行和第2行之间的col1和Col2相同,则认为它们是重复的。我们只需要其中的一排 因此,上述示例的输出将是 Col1 Col2 A B C D E F 或 请帮帮我 谢谢。试
Col1 Col2
A B
B A
C D
D C
E F
F E
如果多行中的col1和Col2以及Col2和col1值相同,则认为它们是重复的。在上例中,第1行和第2行之间的col1和Col2相同,则认为它们是重复的。我们只需要其中的一排
因此,上述示例的输出将是
Col1 Col2
A B
C D
E F
或
请帮帮我
谢谢。试试看
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”。不是“t”。非常感谢你,塞格。。。
delete from myTable t1
where col1 > col2 and exists (select 1
from myTable t2
where t2.col1 = t1.col2 and t2.col2 = t1.col1);
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