原文链接: https://leetcode-cn.com/problems/classes-more-than-5-students
英文原文
Table: Courses
+-------------+---------+ | Column Name | Type | +-------------+---------+ | student | varchar | | class | varchar | +-------------+---------+ (student, class) is the primary key column for this table. Each row of this table indicates the name of a student and the class in which they are enrolled.
Write an SQL query to report all the classes that have at least five students.
Return the result table in any order.
The query result format is in the following example.
Example 1:
Input: Courses table: +---------+----------+ | student | class | +---------+----------+ | A | Math | | B | English | | C | Math | | D | Biology | | E | Math | | F | Computer | | G | Math | | H | Math | | I | Math | +---------+----------+ Output: +---------+ | class | +---------+ | Math | +---------+ Explanation: - Math has 6 students, so we include it. - English has 1 student, so we do not include it. - Biology has 1 student, so we do not include it. - Computer has 1 student, so we do not include it.
中文题目
有一个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 | +---------+
提示:
- 学生在每个课中不应被重复计算。
通过代码
官方题解
方法一:使用 GROUP BY
子句和子查询【通过】
思路
先统计每门课程的学生数量,再从中选择超过 5 名学生的课程。
算法
使用 GROUP BY
和 COUNT
获得每门课程的学生数量。
SELECT
class, COUNT(DISTINCT student)
FROM
courses
GROUP BY class
;
注:使用
DISTINCT
防止在同一门课中学生被重复计算。
| class | COUNT(student) |
|----------|----------------|
| Biology | 1 |
| Computer | 1 |
| English | 1 |
| Math | 6 |
使用上面查询结果的临时表进行子查询,筛选学生数量超过 5 的课程。
SELECT
class
FROM
(SELECT
class, COUNT(DISTINCT student) AS num
FROM
courses
GROUP BY class) AS temp_table
WHERE
num >= 5
;
注:
COUNT(student)
不能直接在WHERE
子句中使用,这里将其重命名为num
。
方法二:使用 GROUP BY
和 HAVING
条件【通过】
算法
在 GROUP BY
子句后使用 HAVING
条件是实现子查询的一种更加简单直接的方法。
MySQL
SELECT
class
FROM
courses
GROUP BY class
HAVING COUNT(DISTINCT student) >= 5
;
统计信息
通过次数 | 提交次数 | AC比率 |
---|---|---|
86299 | 201488 | 42.8% |
提交历史
提交时间 | 提交结果 | 执行时间 | 内存消耗 | 语言 |
---|