如何在Oracle SQL中删除重复项,如果在列中交换相同的值,则元组是重复的?

时间:2014-10-24 22:08:53

标签: sql oracle tuples

以下格式的元组都被视为重复:

A, B, C
A, C, B
B, C, A
B, A, C
C, A, B
C, B, A

如何在Oracle SQL查询中删除元组的重复项(如这些)?

1 个答案:

答案 0 :(得分:2)

使用两列非常简单:

select distinct least(c1,c2), greatest(c1,c2)
from the_table;

以上内容可用于delete声明:

delete from foo
where rowid not in (select min(rowid)
                    from foo
                    group by least(c1,c2), greatest(c1,c2));

有三列,它有点复杂:

select distinct 
         least(c1,c2,c3) as one,
         case 
           when c1 > least(c1,c2,c3) and c1 < greatest(c1,c2,c3) then c1
           when c2 > least(c1,c2,c3) and c2 < greatest(c1,c2,c3) then c2
           when c3 > least(c1,c2,c3) and c3 < greatest(c1,c2,c3) then c3
         end as two,
         greatest(c1,c2,c3) as three
from foo;

因此删除语句有点复杂:

delete from foo 
where rowid not in (
      select min(rowid)
      from foo
      group by least(c1,c2,c3),
               case 
                 when c1 > least(c1,c2,c3) and c1 < greatest(c1,c2,c3) then c1
                 when c2 > least(c1,c2,c3) and c2 < greatest(c1,c2,c3) then c2
                 when c3 > least(c1,c2,c3) and c3 < greatest(c1,c2,c3) then c3
               end,
               greatest(c1,c2,c3))

您没有在表格中指定哪个行。以上将选择“随机”(基于rowid)。