Skip to content

Latest commit

 

History

History
56 lines (44 loc) · 1.15 KB

File metadata and controls

56 lines (44 loc) · 1.15 KB

596. Classes More Than 5 Students

https://leetcode.com/problems/classes-more-than-5-students/

Description

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.


Solution

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

Notes

  1. We need to exclude duplicate students by using DISTINCT
  2. Since we are using GROUP BY, we need to use HAVING instead of WHERE