1、实验目的
(1) 掌握对聚集函数的使用
(2) 掌握对分组的使用
(3) 掌握非关联子查询的用法,了解相关的连接谓词
2、实验预习与准备
(1) 了解Max,Min,Avg,Sum,Count的语法格式
(2) 了解Group by子句的作用
(3) 了解Having子句与Where子句的区别
(4) 了解ANY,ALL的用法
(5) 了解Max,Min,In与ANY,ALL的等价规则
(6) 了解子查询的使用限制
3、实验内容及步骤
(1) 查询每个班学生入学成绩最高分和最低分的差距,列名为“最大分差”
SELECT clno, MAX(point) - MIN(point) AS '最大分差' FROM student GROUP BY clno;
(2) 查询至少选修了三门课程的学生编号
SELECT sno FROM score GROUP BY sno HAVING COUNT(DISTINCT cno) >= 3;
(3)统计各个班级男生和女生的平均年龄及人数。
SELECT clno, sex, AVG(DATEDIFF(CURDATE(), birth)/365) AS '平均年龄', COUNT(*) AS '人数' FROM student GROUP BY clno, sex;
(4)查询至少被两名学生选修的课程名称
SELECT cno, cname FROM course
-> WHERE cno IN (
-> SELECT cno
-> FROM score
-> GROUP BY cno
-> HAVING COUNT(DISTINCT sno) >= 2
-> );
(5) 查询有至少两门课的成绩在90以上的学生姓名
SELECT s.sname FROM student s WHERE (
-> SELECT COUNT(*)
-> FROM score sc
-> WHERE sc.sno = s.sno AND sc.score >= 90
-> ) >= 2;
(6)查询计算机学院至少有两门课的成绩在80以上的女学生学号、姓名和出生日期及其期末成绩的最高分
SELECT s.sno, s.sname, s.birth, MAX(sc.score) AS '期末成绩的最高分'
-> FROM student s
-> JOIN score sc ON s.sno = sc.sno
-> WHERE s.clno LIKE '计算机学院%' AND s.sex = '女'
-> GROUP BY s.sno, s.sname, s.birth
-> HAVING COUNT(DISTINCT sc.cno) >= 2 AND MAX(sc.score) >= 80;
(7)显示学分最高的学生的学号、姓名和入学成绩(使用子查询)
SELECT sno, sname, point
-> FROM student
-> WHERE point = (
-> SELECT MAX(point)
-> FROM student
-> );
(8)查询与“秦建兴”籍贯相同的学生学号、姓名和电话(使用子查询)
SELECT sno, sname, tel
-> FROM student
-> WHERE scurce = (
-> SELECT scurce
-> FROM student
-> WHERE sname = '秦建兴'
-> );
(9)查询入学成绩比“19020301”号班级入学平均成绩高的学生姓名(使用子查询)
SELECT sname
-> FROM student
-> WHERE point > (
-> SELECT AVG(point)
-> FROM student
-> WHERE clno = '19020301'
-> );
(10)查询“数据库原理”课程期末成绩高于该课程平均成绩的学生学号、姓名和期末成绩(使用子查询)
SELECT s.sno, s.sname, sc.score
FROM student s
JOIN score sc ON s.sno = sc.sno
WHERE sc.cno = '数据库原理' AND sc.score > (
SELECT AVG(score)
FROM score
WHERE cno = '数据库原理'
);
(11)查询入学成绩平均值高于“19级金融科技1班”入学成绩平均值的班级编号(使用子查询)
SELECT clno
-> FROM student
-> GROUP BY clno
-> HAVING AVG(point) > (
-> SELECT AVG(point)
-> FROM student
-> WHERE clno = '19级金融科技1班'
-> );
(12)查询选修人数最多的课程号和人数(选做)