如何逐组比较列数并找到它们的最大值

How to compare count of columns with each other in group by groups and find the max of them

首先请参考http://sqlfiddle.com/#!9/7b458/我创建的数据库。 (MYSQL) 现在我有一个问题要找出在哪个课程中有最多的学生被录取。 我就是这样

select course_name from `course-taken`
natural join course;

select course_name,count(course_name) from `course-taken`
natural join course
group by course_name;

参考http://sqlfiddle.com/#!9/7b458/6

现在的问题是如何从计数中找到最大值(course_name) 我试过 Max(count(course_name) [ http://sqlfiddle.com/#!9/7b458/7 ] 但这表明

X Invalid use of group function

所以请任何人帮助我正确查询。
提前致谢。

如果你想要最大计数的课程,并且要么没有平局,要么你可以容忍返回单个记录,那么你可以在这里使用LIMIT

SELECT course_name, COUNT(course_name) AS cnt
FROM course-taken
NATURAL JOIN course
GROUP BY course_name
ORDER BY COUNT(course_name) DESC
LIMIT 1;

只需在 GROUP BY 子句后添加 HAVING 子句即可获得最大 course_name 条记录

HAVING count(course_name) = ( 
                              SELECT max(maxc) FROM 
                         (
                           SELECT course_name, count(course_name) maxc 
                           FROM `course-taken`
                           NATURAL JOIN course
                           GROUP BY course_name)cnt
                         )