SQL(PLSQL),如何选择不重复但计数> 1

时间:2018-12-01 15:32:36

标签: sql database oracle plsql

我有一个带有INVOICE列的表ID_STUFF, STUFF_NAME, E_MAIL。我需要找到具有相同ID_STUFF但具有不同STUFF_NAME或E_MAIL的行。

select distinct g.id_stuff, g.staff_name, g.e_mail from invoice g

显示此: enter image description here

但是对于相同的ID_STUFF,我不需要具有相同值的行。

2 个答案:

答案 0 :(得分:1)

使用exists查找相似的记录:

 select  g.id_stuff, g.staff_name, g.e_mail from invoice g
 where exists 
 (select 1 from invoice g1 where g1.id_stuff =g.id_stuff
  and ( g1.staff_name <> g.staff_name or g1.e_mail <> g.e_mail)

答案 1 :(得分:1)

大概是您想要原始行。如果是这样,我建议您使用exists 两次

select i.*
from invoice i
where exists (select 1
              from invoice i2
              where i2.id_stuff = i.id_stuff and
                    i2.staff_name <> i.staff_name
             ) or
     exists (select 1
             from invoice i2
             where i2.id_stuff = i.id_stuff and
                   i2.e_mail <> i.e_mail
            ) ;

查询可以利用invoice(id_stuff, e_mail)invoice(id_stuff, staff_name)上的索引-在大型表上这将是很大的性能优势。

如果您只想使用id_stuff,那么group by是一个很好的解决方案。您可以使用listagg()获取姓名和电子邮件列表:

select i.id_stuff,
       listagg(e_mail, ',') within group (order by e_mail),
       listagg(staff_name, ',') within group (order by staff_name)
from invoice i
group by i.id_stuff
having min(e_mail) <> max(e_email) or
       min(staff_name) <> max(staff_name);