开发者

Using Count and Max in SQL Query

开发者 https://www.devze.com 2023-04-05 09:43 出处:网络
I have two tables that I am trying to query from, Enrollment and Course开发者_开发知识库. In the course Table, there is just one entry for each course, but in the Enrollment table, there is an entry f

I have two tables that I am trying to query from, Enrollment and Course开发者_开发知识库. In the course Table, there is just one entry for each course, but in the Enrollment table, there is an entry for each student that is enrolled in any course, so there may be 30 entries for one course. My task is to find The course that has the most enrollments, and print out that course name, as well as the number of enrollments for that course. Here is my query so far

select c.CourseCode ,(SELECT count( * ) FROM Enrollment WHERE CourseCode = c.CourseCode) as test from Course c ;

this gives me the results:

CS227 - 29

CS228 - 34

CS309 - 31

CS311 - 25 , ect, which is good, but NOW, how do I print out only the class that has the most enrollments(in this case, CS228). I have tried using the max(), but I can't get anything to work.

Here is the table structure

create table Course( CourseCode char(50), CourseName char(50), PreReq char (6));

create table Enrollment ( CourseCode char(6) NOT NULL, SectionNo int NOT NULL, StudentID char(9) NOT NULL references Student, Grade char(4) NOT NULL, primary key (CourseCode,StudentID), foreign key (CourseCode, SectionNo) references Offering);


Just take the top 1 after ordering by the count.

That is:

Select Top 1 A.CourseCode, Count(*) From Course A inner join Enrollment B on (A.CourseCode=B.CourseCode) 
Group By A.CourseCode
Order By Count(*) DESC

Also - use an inner join as I've shown here rather than a subquery. I do tend to like SubQueries and this one will work but it is just not appropriate in this kind of query!


Based on your comment, I think the blow query is what you want, although it is untested and I am not entirely sure on the HAVING clause being valid. From the documentation on MySQL's page, it seems it should work.

SELECT A.CourseCode, COUNT(*) AS count FROM Course A
JOIN Enrollment B ON A.CourseCode = B.CourseCode
GROUP BY A.CourseCode
HAVING count = MAX(count)

As for performance, I cannot tell if it's a good idea to run a MAX on an aggregate function (probably not).

Otherwise, just use the other query to return the top X and simply run through comparing to the previous number.


SELECT 
      c.CourseCode, 
      c.CourseName,
      COUNT(*) AS cnt 
FROM
      Course AS c
  INNER JOIN
      Enrollment AS e
          ON c.CourseCode = e.CourseCode 
GROUP BY
      c.CourseCode
HAVING 
      COUNT(*) = 
         ( SELECT  
                 COUNT(*) AS cnt 
           FROM
                 Enrollment AS e
           GROUP BY
                 e.CourseCode
           ORDER BY
                 cnt DESC
           LIMIT 1
         )
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号