dept_id | course_id | student_id |
---|---|---|
CS | 101 | 11 |
Math | 101 | 11 |
CS | 101 | 12 |
CS | 201 | 22 |
Math | 301 | 22 |
EE | 102 | 33 |
Math | 201 | 33 |
This is the current sql table called "enrolled" and
I need to select all the departments with the highest number of enrolments.
I tried
SELECT dept_id,COUNT(dept_id) as "enrollments"
FROM enrolled
GROUP BY dept_id;
to get the number of enrollments for each department. But then I am unsure on how to get all the departments with the maximum enrollment.
The final result should be a single column with "CS" and "Math".
3
Answers
You may use
DENSE_RANK
function to give a rank for each department according to the count of enrolled students as the following:See a demo.
You can use HAVING COUNT clause if you have older MySQL version which doesn’t support windows functions
https://dbfiddle.uk/sNcMzVxe
The following query will return the max count which is then used in the having clause
In simple words in your case it will be
having count(dept_id) = 3;
GROUP BY
DENSE_RANK()
. This would always generate the same rank for the same values, in your case it is looking at the total_scores from the the step 1, in the highest oder (ORDER BY
is set todesc
). If you want to do the query other way around you can removeDESC
and the window function will by default work inASC
orderwhere
clause to get the highest enrolled departments