美文网首页
Leetcode_SQL-简单-596-超过5名学生的课

Leetcode_SQL-简单-596-超过5名学生的课

作者: Gaafung峰 | 来源:发表于2020-03-04 22:21 被阅读0次

问题

有一个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:
学生在每个课中不应被重复计算。


准备

create database leecote596;


use leecote596;


create table courses  (
student varchar(20),
class varchar(20));


insert into courses values
('A','Math'),
('B','English'),
('C','Math'),
('D','Biology'),
('E','Math'),
('F','Computer'),
('G','Math'),
('H','Math'),
('I','Math');

解答

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


#方法二:
SELECT class FROM courses
GROUP BY class HAVING COUNT(DISTINCT student) >= 5;

相关文章

网友评论

      本文标题:Leetcode_SQL-简单-596-超过5名学生的课

      本文链接:https://www.haomeiwen.com/subject/aeuwlhtx.html