2012-02-02 67 views
1
SELECT a.ClassName, b.TeacherName, COUNT(c.Class_ID) 
from dbo.Class a 
inner join dbo.Teacher b on a.Teacher_ID = b.Teacher_ID 
left outer join dbo.ClassRegistration c on a.Class_ID = c.Class_ID 
group by a.ClassName, b.TeacherName 

我目前有上面的SQL腳本。它工作正常,想法是顯示ClassName,TeacherName和該類出現在ClassRegistration表中的次數。現在接下來的部分是我有點卡住的地方。 ClassRegistration表也是一個名爲'HasPaid'的列。我需要添加一個第二計數欄,顯示已經支付了多少「ClassRegistration's」。基本SQL - 需要第2個Count()列

回答

1

試試這個:

SELECT 
    a.ClassName, 
    b.TeacherName, 
    COUNT(c.Class_ID), 
    COUNT(CASE c.HasPaid WHEN 1 THEN c.Class_ID ELSE NULL END) 
from dbo.Class a 
inner join dbo.Teacher b 
    on a.Teacher_ID = b.Teacher_ID 
left outer join dbo.ClassRegistration c 
    on a.Class_ID = c.Class_ID 
group by a.ClassName, b.TeacherName 

如果HasPaid是BIT類型的,你可以以這樣的方式簡化了第二計:

SUM(CAST(HasPaid AS INT)) 
+0

完美!奇蹟般有效! – SkonJeet 2012-02-02 08:11:44

+1

已更新的答案。 – 2012-02-02 08:24:46

+1

唉輝煌!我已經從你的帖子中學到了很多東西。再次感謝Oleg! – SkonJeet 2012-02-02 08:24:55

1

如果它是SQL-Server上,如果HasPaid列是類型位,你可以嘗試類似的東西

SELECT a.ClassName, b.TeacherName, COUNT(c.Class_ID), SUM(CASE HasPaid WHEN 1 THEN 1 ELSE 0 END) 
from dbo.Class a 
inner join dbo.Teacher b on a.Teacher_ID = b.Teacher_ID 
left outer join dbo.ClassRegistration c on a.Class_ID = c.Class_ID 
group by a.ClassName, b.TeacherName 
+0

非常感謝Max,與Oleg一樣的原則,現場! – SkonJeet 2012-02-02 08:12:23