Sql count和min

时间:2015-02-06 01:54:34

标签: mysql

我有一个关于如何执行以下sql命令的问题:

报告入学率最低的课程。您应输出课程代码和注册人数。

有问题的表格: - 使用CourseCode,SectionNo,StudentID和Grade

的表注册

我不知道从哪里开始,所以任何帮助都会非常感激。

我尝试了以下根本不起作用的内容:

select p.CourseCode, count(p.StudentID) AS Num_Students
from Enrollment p
where count(p.StudentID) = ( select min( select count(e1.StudentID)) from Enrollment e1 where e1.CourseCode = p.CourseCode)
group by p.CourseCode; 

我正在尝试的结果是只有具有最小学生ID的课程的CourseCode和学生人数。我认为我的逻辑很好但我不太了解sql语法以获得我想要的东西。

1 个答案:

答案 0 :(得分:0)

以最少的非零学生数(最低入学人数)获取课程:

SELECT COUNT(e.studentid) AS lowest_nonzero_count 
  FROM Enrollment e
 GROUP BY e.coursecode
 ORDER BY 1
 LIMIT 1

但是,如果我们想考虑没有任何注册的课程(例如,如果我们认为零是最低入学人数的有效值)

SELECT COUNT(e.studentid) AS lowest_count
  FROM course c
  LEFT
  JOIN enrollment e
    ON e.coursecode = c.coursecode
 GROUP BY c.coursecode
 ORDER BY 1
 LIMIT 1

哪些课程的学生人数最低(非零)?如果我们知道具体的值,我们就可以这样做(用占位符:lowest_nonzero_count表示该值:

SELECT d.coursecode
     , COUNT(d.studentid)
  FROM enrollment d
 GROUP BY d.coursecode 
HAVING COUNT(d.studentid) = :lowest_nonzero_count

我们可以用返回值的子查询替换:lowest_nonzero_count占位符:

SELECT d.coursecode
     , COUNT(d.studentid)
  FROM enrollment d
 GROUP BY d.coursecode 
HAVING COUNT(d.studentid) = 
       ( SELECT COUNT(e.studentid)
           FROM Enrollment e
          GROUP BY e.coursecode
          ORDER BY 1
          LIMIT 1
       )
 ORDER BY d.coursecode     

如果我们想将“零”值视为有效的注册数量:

SELECT b.coursecode
     , COUNT(d.studentid)
  FROM course b
  LEFT
  JOIN enrollment d
    ON d.coursecode = b.coursecode
 GROUP BY b.coursecode
HAVING COUNT(d.studentid) = 
       ( SELECT COUNT(e.studentid)
           FROM course c
           LEFT
           JOIN enrollment e
             ON e.coursecode = c.coursecode
          GROUP BY c.coursecode
          ORDER BY 1
          LIMIT 1
       )
 ORDER BY b.coursecode