使用GROUP BY和COUNT加入不显示空行

时间:2014-08-25 11:27:25

标签: sql sql-server

使用SQL Server 2005.两个表CLASSRESERVATION。我想计算一个类的预订数量,但是我得到了这个错误,其中没有显示空的但有预订被取消的类。我希望显示CLASS表中的所有类。查询:

SELECT C.ClassId AS Id, ISNULL(COUNT(R.ReservationId),0) As numberStudents
FROM CLASS AS C
LEFT JOIN RESERVATION AS R ON R.ClassId = C.ClassId
WHERE R.Cancelled = 0 OR R.ReservationId IS NULL
GROUP BY C.ClassId

我知道课程没有显示,因为确实有预订(R.ReservationId不是NULL)但是Cancelled是1,所以这两个条件都没有在where子句中是真的。我希望ISNULL能够捕获这些情况,但不会显示行。我尝试使用DISTINCT并按R.ClassId进行分组,但不断收到以下错误:

CLASS.ClassId is invalid in the select list. This column is not included in the GROUP BY clause or aggregate function.

我想我看到了逻辑错误。它应该类似于以下内容(我知道这包含语法错误,请视为伪代码)。

SELECT ClassId, Count(Reservations having R.Cancelled = 0)
FROM CLASS LEFT JOIN RESERVATION

我是否需要嵌套查询才能实现此目的?我怎样才能做到这一点? 希望我的问题很清楚。提前谢谢。

2 个答案:

答案 0 :(得分:4)

如果您希望显示所有预订,请将条件移至on子句:

SELECT C.ClassId AS Id, COUNT(R.ReservationId) As numberStudents
FROM CLASS C LEFT JOIN
     RESERVATION R ON
     ON R.ClassId = C.ClassId AND R.Cancelled = 0
GROUP BY C.ClassId;
如果没有匹配,

COUNT()将返回0。无需ISNULL()(或COALESCE())。

答案 1 :(得分:0)

按照预订和左连接的方式将您的预聚合作为查询...类似于:

SELECT 
       C.ClassId AS Id,
       COALESCE( PreQuery.NumStudents,0) As numberStudents
   FROM 
      CLASS C
         LEFT JOIN 
            ( select R.ClassID, count(*) as NumStudents
                 from RESERVATION R 
                 where R.Cancelled = 0
                 group by R.ClassID ) PreQuery
            on C.ClassID = PreQuery.ClassID