基本SQL - 需要第二个Count()列

时间:2012-02-02 08:04:32

标签: sql join count group-by

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”。

2 个答案:

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

答案 1 :(得分:1)

如果它在SQL-Server上,并且HasPaid列的类型为bit,您可以尝试类似的东西

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