如何从同一个表中选择唯一的元组

时间:2014-10-12 19:25:25

标签: sql database oracle

我希望找到所有从

一起注册两个或更多部分的不同学生

注册(sid *,年级,dname *,cno *,sectno *)

其中每个部分由(dname *,cno *,sectno *)

唯一标识

3 个答案:

答案 0 :(得分:3)

您可以自行加入标识某个部分的列,并指定e1.sid < e2.sid以仅获取每对学生一次。

select e1.sid, e2.sid from enroll e1
join enroll e2 on e1.dname = e2.dname
and e1.cno = e2.cno
and e1.secno = e2.sectno
where e1.sid < e2.sid
group by e1.sid, e2.sid
having count(*) > 1

答案 1 :(得分:1)

/*
with enroll as (
select 1 sid, 'dname' dname, 1 cno, 1 secno from dual union all
select 1 sid, 'dname' dname, 1 cno, 1 secno from dual union all
select 2 sid, 'dname' dname, 1 cno, 1 secno from dual union all
select 3 sid, 'dname' dname, 1 cno, 1 secno from dual union all
select 1 sid, 'dname' dname, 2 cno, 2 secno from dual union all
select 2 sid, 'dname' dname, 2 cno, 2 secno from dual
)
*/
select e1.sid, e2.sid from enroll e1
join enroll e2 on e1.dname = e2.dname
and e1.cno = e2.cno
and e1.secno = e2.secno
where e1.sid < e2.sid
group by e1.sid, e2.sid
having count(*) >= 2;

(但如果一个sid在同一部分登记的时间超过一次,则此查询将无法正常工作)

答案 2 :(得分:1)

with enroll as (
select 1 sid, 'dname' dname, 1 cno, 1 secno from dual union all
select 1 sid, 'dname' dname, 1 cno, 1 secno from dual union all
select 2 sid, 'dname' dname, 1 cno, 1 secno from dual union all
select 3 sid, 'dname' dname, 1 cno, 1 secno from dual union all
select 3 sid, 'dname' dname, 1 cno, 1 secno from dual union all
select 1 sid, 'dname' dname, 2 cno, 2 secno from dual union all
select 2 sid, 'dname' dname, 2 cno, 2 secno from dual
)
select rn,sid from (
select row_number() over (partition by sid order by dname) as rn ,sid
from enroll ) 
where rn>1

使用row_number()

如果一个sid多次注册同一部分

,则此查询可正常工作
如果需要,可以使用

distinct

with enroll as (
select 1 sid, 'dname' dname, 1 cno, 1 secno from dual union all
select 1 sid, 'dname' dname, 1 cno, 1 secno from dual union all
select 2 sid, 'dname' dname, 1 cno, 1 secno from dual union all
select 3 sid, 'dname' dname, 1 cno, 1 secno from dual union all
select 3 sid, 'dname' dname, 1 cno, 1 secno from dual union all
select 1 sid, 'dname' dname, 2 cno, 2 secno from dual union all
select 4 sid, 'dname' dname, 2 cno, 2 secno from dual union all
select 2 sid, 'dname' dname, 2 cno, 2 secno from dual
)
select distinct  sid from (
select row_number() over (partition by sid order by dname) as rn ,sid
from enroll ) 
where rn>1

<强>输出

>        SID
> ----------
>          1
>          2
>          3