项目3:查询出超过5名学生的课程(难度:简单)
创建如下所示的courses 表 ,有: student (学生) 和 class (课程)。
例如,表:
+---------+------------+
| student | class |
+---------+------------+‘’
| A | Math |
| B | English |
| C | Math |
| D | Biology |
| E | Math |
| F | Computer |
| G | Math |
| H | Math |
| I | Math |
| A | Math |
+---------+------------+
---- 创建表
CREATE TABLE courses ( student varchar(50) NOT NULL, class varchar(50) NOT NULL);
--插入数据
INSERT INTO `courses` VALUES ('A', 'Math'); INSERT INTO `courses` VALUES ('B', 'English'); INSERT INTO `courses` VALUES ('C', 'Math'); INSERT INTO `courses` VALUES ('D', 'Biology'); INSERT INTO `courses` VALUES ('E', 'Math'); INSERT INTO `courses` VALUES ('F', 'Computer'); INSERT INTO `courses` VALUES ('G', 'Math'); INSERT INTO `courses` VALUES ('H', 'Math'); INSERT INTO `courses` VALUES ('I', 'Math'); INSERT INTO `courses` VALUES ('A', 'Math');
编写一个 SQL 查询,列出所有超过或等于5名学生的课。
应该输出:
+---------+
| class |
+---------+
| Math |
+---------+
注意点:学生在每个课中不应被重复计算(在本案例里student字段有相关的,要注意剔除相同学生后再算课程被选的次数)
方法1:用子查询
SELECT t.class FROM (SELECT DISTINCT * FROM courses) t GROUP BY t.class HAVING count(t.class)>=5
方法2:用distinct 对学生字段去重后再计算
SELECT class FROM courses GROUP BY class HAVING count(DISTINCT student)>=5