2017-04-17 53 views
0

一直試圖解決此查詢幾個小時。SQL:在兩門課程上顯示具有相同教師的學生

我有以下表格:

Student 
    (StudenNumber* INT, ID TEXT, Fname TEXT, Lname TEXT, Institute TEXT, EnrollYear INT) 

    Teacher 
    (ID* TEXT, Fname TEXT, Lname TEXT, Insitutue TEXT) 

    Course 
    (ID* TEXT, Name TEXT, Type TEXT, Weeks INT, Period INT, Year INT, Subject TEXT, Teacher TEXT) 

    Institute 
    (Name* TEXT, Faculty TEXT) 

    Subject 
    (Name* TEXT, Examination TEXT, Insitute TEXT) 

    Grade 
    (Course* TEXT,Student* INT, Grade INT) 

    Examination 
    (ID* TEXT, ExaminationName* TEXT) 

,我試圖讓顯示所有有過同樣的老師在兩個療程(刪除重複)的學生。

我的查詢沒有返回正是我要找:

SELECT DISTINCT E.Fname, E.Lname 
FROM STUDENT E 
WHERE EXISTS (SELECT COUNT(A.TEACHER) 
       FROM COURSE A, COURSE B 
       WHERE A.Teacher = B.Teacher 
       GROUP BY Teacher 
       having COUNT(*) = 2); 
+0

您的子查詢需要引用E.(不好的表別名選擇...) – jarlh

回答

0

您需要使用COURSE的映射表,它的每個學生連接到課程(因此教師)。從那裏,你可以按學生/老師對進行分組,只計算行數。

SELECT 
    s.fname || ' ' || s.lname as student_name 
    ,t.fname || ' ' || f.lname as teacher_name 
    ,count(1) as courses_together 
FROM 
    COURSE c 
LEFT JOIN 
    TEACHER t  --grab teachers' names 
    ON 
     c.teacher = t.id 
LEFT JOIN 
    GRADE g  --this is our map table linking courses to students 
    ON 
     c.id = g.course 
LEFT JOIN 
    STUDENT s 
    ON 
     g.student = s.id 
GROUP BY 
    student_name, last_name 
HAVING 
    count(1) > 1 
+0

我得到NULL值作爲回報。正確的答案應該返回2名學生。 – Jared

+0

其中一個連接失敗和/或某些字段中沒有文本。你是否只獲得空值,或者你是否獲得NULL和兩個學生? – ScottieB

相關問題