3

假设有 3 个这样的表:

老师:

teacher_id, name, ... 

学生:

student_id, teacher_id, ... 

班级:

class_id, teacher_id, ... 

是否有一个 SQL 查询来获取每个老师分配了多少学生和班级?

结果应该是这样的:

teacher_id  name    students    classes 
t_001       AAA        3           2 
t_002       BBB        1           2 
...
4

3 回答 3

2

尝试这样的事情:

SELECT 
    t.teacher_id, t.name,
    Classes = (SELECT COUNT(*) FROM Class c WHERE c.teacher_id = t.teacher_id),
    Students = (SELECT COUNT(*) FROM Student s WHERE s.teacher_id = t.teacher_id)
FROM teacher t
于 2012-08-11T11:38:36.950 回答
0
with teacher_students as (
  select t.teacher_id,
         t.name,
         count(s.student_id) as students
    from Teacher t
    left outer join Student s
      on t.teacher_id = s.teacher_id
   group by t.teacher_id, t.name
),
teacher_classes as (
  select t.teacher_id,
         count(c.class_id) as classes
    from Teacher t
    left outer join Class c
      on t.teacher_id = c.teacher_id
   group by t.teacher_id
)
select ts.teacher_id,
       ts.name,
       ts.students,
       tc.classes
  from teacher_students ts
  join teacher_classes tc
    on ts.teacher_id = tc.teacher_id
于 2012-08-11T13:09:27.497 回答
-1

尝试这个:

SELECT       T.TEACHER_ID
           , T.NAME,
           , COUNT(C.TEACHER_ID ) AS   CLASSES
           , COUNT(S.TEACHER_ID ) AS   STUDENTS
FROM TEACHER T 
LEFT OUTER JOIN CLASS C
ON  T.TEACHER_ID = C.TEACHER_ID
LEFT OUTER JOIN STUDENT S 
ON T.TEACHER_ID = S.TEACHER_ID
GROUP BY T.TEACHER_ID, T.NAME
于 2012-08-11T11:50:43.517 回答