删除特定列SQL中具有重复项的条目

时间:2018-01-25 15:34:15

标签: sql oracle

我有3列:A B C.我只想要在col A中共享相同值但在B和C中具有不同值的行。

1 | item1 | Jan | Amy
2 | item1 | Feb | Amy
3 | item2 | Mar | Bob
4 | item2 | Mar | Bill
5 | item3 | Apr | Charles
6 | item3 | May | Doug
7 | item4 | Jun | Felix

上面的例子。我希望它显示第5,6和7行。

有没有好办法呢?

2 个答案:

答案 0 :(得分:1)

如果我理解你的需要,这可能是一种方式,只需对表进行一次扫描:

with test(id, a, b, c) as
(
    select 1, 'item1', 'Jan', 'Amy' from dual union all
    select 2, 'item1', 'Feb', 'Amy' from dual union all
    select 3, 'item2', 'Mar', 'Bob' from dual union all
    select 4, 'item2', 'Mar', 'Bill' from dual union all
    select 5, 'item3', 'Apr', 'Charles' from dual union all
    select 6, 'item3', 'May', 'Doug' from dual union all
    select 7, 'item4', 'Jun', 'Felix' from dual
)
select id, a, b, c
from (
        select id, a, b, c,
               count(distinct b) over (partition by a) count_b,
               count(distinct c) over (partition by a) count_c,
               count(1)          over (partition by a) count_a
        from test
     )
where count_a = count_b
  and count_a = count_c 

结果:

        ID A     B   C
---------- ----- --- -------
         5 item3 Apr Charles
         6 item3 May Doug
         7 item4 Jun Felix

答案 1 :(得分:0)

使用not exists

select t.*
from t
where not exists (select 1
                  from t t2
                  where t2.a = t.a and
                        (t2.b = t.b or t2.c = t.c) and
                        t2.id <> t.id
                 );

这假定列唯一标识每一行。如果您没有,并且表没有重复项,则可以使用:

select t.*
from t
where not exists (select 1
                  from t t2
                  where t2.a = t.a and
                        (t2.b = t.b or t2.c = t.c) and
                        not (t2.b = t.b and t2.c = t.c)
                 );