前言:

创建以下四张表:①:课程表

②:成绩表

③:学生表

④:教师表

1.查询课程编号为“”01“”的课程比“02”的课程成绩高的所有学生的学号(重点)

SELECT
a.s_id "s_no",
c.s_name,
a.s_score "01",
b.s_score "02"
FROM
( SELECT s_id, c_id, s_score FROM score WHERE c_id = '01' ) AS a
INNER JOIN ( SELECT s_id, c_id, s_score FROM score WHERE c_id = '02' ) AS b ON a.s_id = b.s_id
INNER JOIN student AS c ON c.s_id = a.s_id
WHERE
a.s_score > b.s_score

结果如图所示

浅谈思路:( SELECT s_id, c_id, s_score FROM score WHERE c_id = '01' ) AS a 首先先从课程表中查询出选了01课的所有学生建为a表

INNER JOIN ( SELECT s_id, c_id, s_score FROM score WHERE c_id = '02' ) AS b ON a.s_id = b.s_id 同样从课程表中查询选了02课的所有学生建为b表,并且进行连接。连接条件为:

ON a.s_id = b.s_id   采用学生编号将这两张表连接起来

INNER JOIN student AS c ON c.s_id = a.s_id 再连接一张学生表,把学生的名字查询出来

WHERE
a.s_score > b.s_score  查询01课的成绩大于02课的成绩

SELECT
a.s_id "s_no",
c.s_name,
a.s_score "01",
b.s_score "02"
FROM

最后查询出学生编号,学生姓名,学生的01课程成绩,02课程成绩即可。

 

2.查询出平均成绩大于60分的学生的学号和成绩

Select s_id,avg(s_score)
from score
GROUP BY s_id HAVING avg(s_score)>60

查询结果如图所示

浅谈思路:

Select s_id,avg(s_score) 查询出学生的ID,和成绩的平均值
from score  从成绩表中查询
GROUP BY s_id HAVING avg(s_score)>60 

group by 分组 [学号]
having 分组条件 [平均成绩大于60分:avg(成绩 ) >60]

 

引用一下https://blog.csdn.net/qq_38962853/article/details/73838626解释一下group by的用法

当SELECT 后 既有 表结构本身的字段,又有需要使用聚合函数(COUNT(),SUM(),MAX(),MIN(),AVG()等)的字段,就要用到group by分组,查询的限定条件里有需要用聚合函数计算的字段时也需要用分组,比如:
select avg(grade) from cs
查询选课表(cs)中学生的总成绩(grade);这里就不用分组;
又如:
select sno,sum(grade) from cs group by sno
查询选课表里每个学生的总成绩,这里就要用分组,分组的依照字段必须是select 后没有被计算过的原始字段;
以上是分组用法。

posted on 2022-06-16 00:17  小熊冰淇淋  阅读(31)  评论(0编辑  收藏  举报