我有一张包含以下数据的表格。
Col1 Col2
A B
B A
C D
D C
E F
F E
如果(col1和Col2)和(col2和Col1)值在多行中相同,则它们被视为重复。在上面的示例中,Col1和Col2在第1行和第2行之间相同,它们被认为是作为重复。我们只需要一行。
所以上面例子的输出将是,
Col1 Col2
A B
C D
E F
或
Col1 Col2
B A
D C
F E
请帮帮我。
谢谢..
答案 0 :(得分:4)
试试这个:
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
答案 1 :(得分: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);