https://leetcode.com/problems/classes-more-than-5-students/
There is a table courses with columns: student and class
Please list out all classes which have more than or equal to 5 students.
For example, the table:
+---------+------------+
| student | class |
+---------+------------+
| A | Math |
| B | English |
| C | Math |
| D | Biology |
| E | Math |
| F | Computer |
| G | Math |
| H | Math |
| I | Math |
+---------+------------+
Should output:
+---------+
| class |
+---------+
| Math |
+---------+
Note: The students should not be counted duplicate in each course.
This is a pretty straight forward question.
What we want to do is to get a COUNT of the students in each class, then filter out those with less than 5 students.
SELECT class
FROM courses
GROUP BY class
HAVING COUNT(DISTINCT student) >= 5- We need to exclude duplicate students by using
DISTINCT - Since we are using
GROUP BY, we need to useHAVINGinstead ofWHERE