有一个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 + 临时表 + where cnt >=5
- 第一次提交
select a.class from (
select distinct class, count(class) as cnt
from courses
group by class
) as a
where a.cnt >= 5
结果错误:
输入:
{"headers": {"courses": ["student", "class"]}, "rows": {"courses": [["A", "Math"], ["B", "English"], ["C", "Math"], ["D", "Biology"], ["E", "Math"], ["F", "Math"], ["A", "Math"]]}}
输出
{"headers": ["class"], "values": [["Math"]]}
预期结果
{"headers":["class"],"values":[]}
看了评论区,学生A 重修了数学。哈哈
想到DISTINCT 去重,又看了评论区答案一波。
- 第二次提交
select a.class from (
select class ,count(distinct student ) as cnt
from courses
group by class
) as a
where a.cnt >= 5
distinct 居然还能在count()函数里面用,学到了。
- 第三次提交(来自评论区大佬)
SELECT CLASS
FROM COURSES
GROUP BY CLASS
HAVING COUNT(DISTINCT STUDENT) >= 5;
先group by分组,再用having count() + distinct去重计数筛选。
写的也优雅。
总结
distinct 基本用法。
having 跟在聚合函数后面做条件筛选。
临时表 使用。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/classes-more-than-5-students
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
网友评论