如何计算SQL Server中每位老师的学生和班级?

时间:2012-08-11 11:29:31

标签: sql

假设有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 
...

3 个答案:

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

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

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