美文网首页
(LeetCode596:数据库) 超过5名学生的课

(LeetCode596:数据库) 超过5名学生的课

作者: lconcise | 来源:发表于2019-04-20 22:14 被阅读0次

有一个courses 表 ,有: student (学生) 和 class (课程)。

请列出所有超过或等于5名学生的课。

+---------+------------+
| student | class      |
+---------+------------+
| A       | Math       |
| B       | English    |
| C       | Math       |
| D       | Biology    |
| E       | Math       |
| F       | Computer   |
| G       | Math       |
| H       | Math       |
| I       | Math       |
+---------+------------+

应该输出:

+---------+
| class   |
+---------+
| Math    |
+---------+

Solution:
方法一:
select class from courses group by class having count(distinct student)>=5;

SELECT
    class
FROM
    courses
GROUP BY
    class
HAVING
    count(DISTINCT student) >= 5;

方法二:
方法二相比方法一效率低些。

select class from (select DISTINCT * from course) a GROUP BY class where count(1)>=5;

SELECT
    class
FROM
    (SELECT DISTINCT * FROM course) a
GROUP BY
    class
WHERE
    count(1) >= 5;

相关文章

网友评论

      本文标题:(LeetCode596:数据库) 超过5名学生的课

      本文链接:https://www.haomeiwen.com/subject/hgfyaftx.html