2 minutes

# LeetCode[596] Classes More Than 5 Students

## Question

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.

## SQL Schema

```
Create table If Not Exists courses (student varchar(255), class varchar(255))
Truncate table courses
insert into courses (student, class) values ('A', 'Math')
insert into courses (student, class) values ('B', 'English')
insert into courses (student, class) values ('C', 'Math')
insert into courses (student, class) values ('D', 'Biology')
insert into courses (student, class) values ('E', 'Math')
insert into courses (student, class) values ('F', 'Computer')
insert into courses (student, class) values ('G', 'Math')
insert into courses (student, class) values ('H', 'Math')
insert into courses (student, class) values ('I', 'Math')
```

## My Interesting Code

```
select class
from courses
group by class having count(distinct student) >= 5
```

## My Perspective

This question is very simple. However, you should consider the redundant students in the same class, using “distinct”.

Also, there is a useful link, and I think it can help you. (chinese version)

leetcode" #595 easy sql advertising product manager classes more than 5 students

243 Words

2021-01-13 15:10