Table:
sql:
SELECT ClassID,COUNT(case when Sex='男' then 1 else null end) FROM Student GROUP BY ClassID
Result:
既然是先执行的where再执行的select,那就不用where用case好了,case就是在select里的,可以很好的解决你的问题。
流弊
WITH a AS( SELECT DISTINCT ClassId FROM Students WITH(nolock) ) SELECT a.ClassId, isnull(COUNT(b.ClassId), 0) FROM a LEFT JOIN Students b WITH(nolock) ON a.ClassId = b.ClassId AND b.gender = 1 GROUP BY a.ClassId
SELECT Stu.ClassID,Count(SELECT * FROM Student AS Stu2 Where Stu2.ClassID = Stu.ClassID AND Stu2.Gender = 1) FROM Student AS Stu GROUP BY ClassID
student 表 左联自己