【lc-database】596.超过5名学生的课

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

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

1.groud by 和 having

select class from courses  GROUP BY class having count(DISTINCT student) >=5;

思路: 计算超过5名学生的课程,因此需要使用分组groud by 分组后 就可以统计了 但是where是在groud by之前进行行级别的过滤 而having是在组级别上进行过滤,因此就可以确定使用 groud by+having组合来解决 去重的化 我想了很久还是不会,看了下答案 答案上是这么写的 count()函数里进行去重 这里重点标记一下。

2.ground by +子查询

SELECT
    class
FROM
    (SELECT
        class, COUNT(DISTINCT student) AS num
    FROM
        courses
    GROUP BY class) AS temp_table
WHERE
    num >= 5
;

思路:前提是需要进行分组操作,所以select class ,count(distinct student) from courses group by class 可以查到分组之后的信息了 ,将查询的表 当作一个临时表来进行操作。

posted @ 2019-12-10 16:05  qxlxi  阅读(86)  评论(0编辑  收藏  举报