Classes More Than 5 Students

题目

There is a tablecourseswith columns:studentandclass

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.

思路分析

这是一道group by的题型,但是要注意的是原始表中可能有重复的行,所以要先对原始的table进行去重,然后在产生的新表中进行group by和having

# Write your MySQL query statement below
select class
from (select distinct class, student
      from courses
) as distinctClass
group by class
having count(class)>=5;

这道题的另外一个解法是,继续使用原始表,但是在having的时候使用去重后的student

# Write your MySQL query statement below
select class
from courses
group by class
having count(distinct student)>=5;

results matching ""

    No results matching ""