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 に答える