2012-08-11 66 views
3

假定3個表是這樣的:如何統計SQL Server中每位教師的學生和班級?

老師:

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 
... 
+0

歡迎StackOverflow上:如果您發佈的代碼,XML或數據樣本,**請**突出顯示te中的那些行xt編輯器,並點擊編輯器工具欄上的「代碼示例」按鈕(「{}」),以良好地格式化和語法突出顯示它!那麼你不需要那些雜亂的' '和'
'標籤! – 2012-08-11 11:37:19

回答

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

我喜歡這個,很棒。 – Ouyangzhi 2012-08-11 14:13:14

0

試試這個:

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 
+1

這會給錯誤的計數。它使用所有教師級行對所有Teacher-Student行進行置換。有3名學生和2個班級的老師將被列爲6名學生和6個班級。 – dbenham 2012-08-11 13:14:27

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 
相關問題