SQL:在两门课程中向同一位老师展示学生

时间:2017-04-17 17:14:20

标签: 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);

1 个答案:

答案 0 :(得分: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