2016-11-26 54 views
2

Student_table學生報名參加同一課程

std_name course_enrolled 
S1   C1 
S1   C2 
S2   C1 
S3   C4 
S4   C1 
S4   C2 
S5   C1 

我想選擇誰已經報名參加同一門課程像S1 & S4報名參加C1 C2 &學生,S2 & S5報名參加C1 ......這樣的。這只是表的一個snopshot,實際的表將包含更多的數據。 請給我同樣的SQL查詢。

+0

請用您正在使用的數據庫標記您的問題。另外,這些課程必須完全一樣嗎? –

+0

Oracle數據庫。相同的課程意味着它應該是相同的。我僅僅爲此描述了描述。謝謝 –

回答

0

使用標準的SQL,你可以這樣做:

with s as (
     select s.*, count(*) over (partition by std_name) as num_courses 
     from student_table s 
    ) 
select s1.std_name, s2.std_name 
from s s1 join 
    s s2 
    on s1.std_name < s2.std_name and 
     s1.num_courses = s2.num_courses and 
     s1.course_enrolled = s2.course_enrolled 
group by s1.std_name, s2.std_name 
having count(*) = max(s1.num_courses); 

這是一個相當棘手的自聯接。但基本上它是說「匹配課程的數量是一個學生參加的課程的數量。」

1
create table student_enrolled(student varchar2(20),course varchar2(20)); 

insert into student_enrolled values('S1',   'C1'); 
insert into student_enrolled values('S1',   'C2'); 
insert into student_enrolled values('S2',   'C1'); 
insert into student_enrolled values('S3',   'C4'); 
insert into student_enrolled values('S4',   'C1'); 
insert into student_enrolled values('S4',   'C2'); 
insert into student_enrolled values('S5',   'C1'); 

select * from student_enrolled; 

STUDENT    COURSE    
-------------------- -------------------- 
S1     C1     
S1     C2     
S2     C1     
S3     C4     
S4     C1     
S4     C2     
S5     C1  



select s1.student , s2.student, s1.course as common_course 
from student_enrolled s1 join student_enrolled s2 on (s1.course=s2.course) 
where 
-- to not show student with himself 
s1.student<>s2.student and 
not exists (
    -- all courses enrolled by s2 not enrolled by s1 
    select 1 from student_enrolled s3 where s3.student=s2.student and not exists (select 1 from student_enrolled s4 where s4.student=s1.student and s4.course=s3.course)) 
and 
not exists (
    -- all courses enrolled by s1 not enrolled by s2 
    select 1 from student_enrolled s5 where s5.student=s1.student and not exists (select 1 from student_enrolled s6 where s6.student=s2.student and s6.course=s5.course)) 

order by 1,2 ; 

STUDENT1    STUDENT2    COMMON_COURSE  
-------------------- -------------------- -------------------- 
S1     S4     C1     
S1     S4     C2     
S2     S5     C1     
S4     S1     C1     
S4     S1     C2     
S5     S2     C1