Leetcode No.596 超过5名学生的课(总结having与where的区别)

    技术2022-07-16  86

    难度:简单

    有一个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 | +---------+

    Note: 学生在每个课中不应被重复计算。

    解答:

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

    总结:

    也是一道基础简单题,考察以什么作为group by字段,和去重distinct的用法。注意点:having的使用,要用在group by之后。

    补充:having与where的区别

    1、执行的顺序不一样 having是在分组之后的基础之上做筛选,用在group by之后 where是在分组之前使用的 2、使用的地方不同 having只能用在select语句中, 而where可以用于select,update,delete,drop,alter等语句中 3、子句存在区别 having子句可以用聚合函数(sunm,count,avg,min,max……) 而where不可以用聚合函数

    Processed: 0.013, SQL: 9