计数记录所需的SQL查询

时间:2016-03-15 18:09:37

标签: mysql

我的情况是这样的。我需要提供学生的姓名和他们所获得的特定成绩的数量(在这种情况下为A级)。将第一个查询视为:

SELECT studentID, fullname
FROM tblStudents

下一个查询是:

SELECT studentID, grade, Count(grade) AS CountOfGrade
FROM tblResults
GROUP BY studentID, grade
HAVING grade="A";

我可以将这些结合起来,这样我就可以通过加入查询来显示每个学生的A等级数:

SELECT tblStudents.studentID, tblStudents.fullname, tblResults.grade, Count(tblResults.grade) AS CountOfGrade
FROM tblStudents INNER JOIN tblResults ON tblStudents.studentID = tblResults.studentID 
GROUP BY tblStudents.fullname, tblResults.grade
HAVING tblResults.grade="A";

然而,它没有返回没有A级学生的名字,只有至少有1名学生的名字。我尝试过LEFT加入而不是INNER,但这似乎没有帮助。

我怎样才能实现这一点,以便我得到零计数?例如:

Name    Grade   GradeCount
Bob     A       1
Jim     A       0 
Sarah   A       4
etc 

2 个答案:

答案 0 :(得分:2)

尝试LEFT JOIN到第二个查询生成的派生表:

SELECT t1.studentID, 
       t1.fullname, 
       'A' AS grade, 
       COALESCE(t2.CountOfGrade, 0) AS CountOfGrade
FROM tblStudents AS t1
LEFT JOIN (
   SELECT studentID, COUNT(grade) AS CountOfGrade
   FROM tblResults
   WHERE grade = 'A'
   GROUP BY studentID
) AS t2 ON t1.studentID = t2.studentID

注意:实际上没有必要按grade字段进行分组,因为您只需要grade = 'A'条记录。您只需使用WHERE子句即可。

答案 1 :(得分:1)

如果字段等级始终等于参数:GRADE,也可以使用子选择执行此操作。

SELECT NAME, :GRADE GRADE , 
       (SELECT COUNT(1) 
          FROM GRADES 
         WHERE GRADE = :GRADE 
           AND GRADES.STUDENT_ID = S.STUDENT_ID) GRADECount  
  FROM STUDENTS S

现在您可以使用参数级别'A'进行查询:

SELECT NAME, 'A' GRADE , 
       (SELECT COUNT(1) 
          FROM GRADES 
         WHERE GRADE = 'A'
           AND GRADES.STUDENT_ID = S.STUDENT_ID) GRADECount  
 FROM STUDENTS S