GROUP BY、HAVING、AS 的用法小例子
需求:
查询选休了5门课程的学生的姓名
分析:
1.
先从 t_sc 表中查出 选了5门课的学生的学号:
SELECT COUNT(code) AS countCourse,sid FROM t_sc GROUP BY sid HAVING countCourse =5
(使用 group by 子句对数据按 sid 进行分组;对group by 子句形成的组运行聚集函数 COUNT 计算每一组的值;最后用 having 子句去掉不符合条件的组)
SELECT sid FROM (SELECT COUNT(code) AS countCourse,sid FROM t_sc GROUP BY sid HAVING countCourse =5) AS a
(AS a 表示把一个结果集 当作一个表来查询)
2.
根据学号,查询名字
SELECT sname FROM t_student WHERE sid in ( SELECT sid FROM (SELECT COUNT(code) AS countCourse,sid FROM t_sc GROUP BY sid HAVING countCourse =5) AS a )