加载中...
596-超过5名学生的课(Classes More Than 5 Students)
发表于:2021-12-03 | 分类: 简单
字数统计: 526 | 阅读时长: 2分钟 | 阅读量:

原文链接: 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 BYCOUNT 获得每门课程的学生数量。

[snippet1-MySQL]
SELECT class, COUNT(DISTINCT student) FROM courses GROUP BY class ;

注:使用 DISTINCT 防止在同一门课中学生被重复计算。

| class    | COUNT(student) |
|----------|----------------|
| Biology  | 1              |
| Computer | 1              |
| English  | 1              |
| Math     | 6              |

使用上面查询结果的临时表进行子查询,筛选学生数量超过 5 的课程。

[solution1-MySQL]
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 BYHAVING 条件【通过】

算法

GROUP BY 子句后使用 HAVING 条件是实现子查询的一种更加简单直接的方法。

MySQL

[solution2-MySQL]
SELECT class FROM courses GROUP BY class HAVING COUNT(DISTINCT student) >= 5 ;

统计信息

通过次数 提交次数 AC比率
86299 201488 42.8%

提交历史

提交时间 提交结果 执行时间 内存消耗 语言
上一篇:
595-大的国家(Big Countries)
下一篇:
598-范围求和 II(Range Addition II)
本文目录
本文目录