Classes More Than 5 Students Problem
#596
Description
LeetCode Problem 596.
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 |
+---------+
Solution
Approach: GROUP BY and HAVING
We count the students of each class and keep the classes with at least 5.
GROUP BY classgives one group per class.HAVINGfilters groups after they are formed (WHEREruns before grouping and can't use the count). Keep a class whenCOUNT(DISTINCT student) >= 5.
Count distinct students: the table has no key, so the same student can be listed twice in the same class, and that must not count as two students. In the test data English has 5 rows but only 4 different students (B appears twice), so it is not in the result.
Note the condition is "more than or equal to 5", so >= 5, not > 5.
The Pandas version counts unique students per class with nunique and keeps the classes where that count is at least 5.
SELECT class
FROM courses
GROUP BY class
HAVING COUNT(DISTINCT student) >= 5;