前言
sql真的非常灵活,一个题目可能有很多很多种解法,我记录的只是我自己的一个解题思路,如果大家有更好的不同解法欢迎在评论区一起探讨
ps:有些题可能解法会重复,比如求大于,我们下一个题可能是求小于,大家如果第一遍没有做出来,看了我写的之后有了思路,可以试一下反面的解法。
数据库表结构介绍
学生表
课程表
成绩表
教师表
1-6 检索"01"课程分数小于60,按分数降序排列的学生信息
SELECT
a.*, b.c_id,
b.s_score
FROM
student a,
score b
WHERE
a.s_id = b.s_id
AND b.c_id = '01'
AND b.s_score < 60
ORDER BY
b.s_score DESC;
结果如下:
1-7 按平均成绩从高到低显示所有学生的所有课程的成绩以及平均成绩
SELECT
a.s_id,
(
SELECT
s_score
FROM
score
WHERE
s_id = a.s_id
AND c_id = '01'
) AS 语文,
(
SELECT
s_score
FROM
score
WHERE
s_id = a.s_id
AND c_id = '02'
) AS 数学,
(
SELECT
s_score
FROM
score
WHERE
s_id = a.s_id
AND c_id = '03'
) AS 英语,
round(avg(s_score), 2) AS 平均分
FROM
score a
GROUP BY
a.s_id
ORDER BY
平均分 DESC;
结果如下:
1-8 查询各科成绩最高分、最低分和平均分:以如下形式显示:课程ID,课程name,最高分,最低分,平均分,及格率,中等率,优良率,优秀率
– round 函数主要是进行数值的小数点保留
– 1、round(x,d) x指要处理的数,d是指保留几位小数。这里有个值得注意的地方是,d可以是负数,这时是指定小数点左边的d位整数位为0,同时小数位均为0;
– 2、round(x) ,其实就是round(x,0),也就是默认d为0;
SELECT
a.c_id,
b.c_name,
MAX(s_score),
MIN(s_score),
AVG(s_score),
ROUND(
100 * (
SUM(
CASE
WHEN a.s_score >= 60
AND a.s_score <= 90 THEN
1
ELSE
0
END
) / SUM(
CASE
WHEN a.s_score THEN
1
ELSE
0
END
)
),
2
) AS 及格率,
ROUND(
100 * (
SUM(
CASE
WHEN a.s_score >= 70
AND a.s_score <= 80 THEN
1
ELSE
0
END
) / SUM(
CASE
WHEN a.s_score THEN
1
ELSE
0
END
)
),
2
) AS 中等率,
ROUND(
100 * (
SUM(
CASE
WHEN a.s_score >= 80
AND a.s_score <= 90 THEN
1
ELSE
0
END
) / SUM(
CASE
WHEN a.s_score THEN
1
ELSE
0
END
)
),
2
) AS 优良率,
ROUND(
100 * (
SUM(
CASE
WHEN a.s_score >= 90 THEN
1
ELSE
0
END
) / SUM(
CASE
WHEN a.s_score THEN
1
ELSE
0
END
)
),
2
) AS 优秀率
FROM
score a
LEFT JOIN course b ON a.c_id = b.c_id
GROUP BY
a.c_id
结果如下:
1-9 查询学生的总成绩并进行排名
SELECT
b.*, a.c_id, a.s_score,
(SELECT COUNT(DISTINCT a2.s_score)
FROM score a2
WHERE a2.c_id = a.c_id AND a2.s_score >= a.s_score) AS rk
FROM
score a
JOIN student b ON a.s_id = b.s_id;
结果如下:文章来源:https://www.toymoban.com/news/detail-736033.html
2-0 查询学生的总成绩并进行排名
SELECT
suma.*, (
SELECT
count(avgscore)
FROM
(
SELECT
a.s_id,
avg(a.s_score) avgscore
FROM
score a
GROUP BY
a.s_id
) sumb
WHERE
suma.avgscore < sumb.avgscore
) + 1 rk
FROM
(
SELECT
a.s_id,
avg(a.s_score) avgscore
FROM
score a
GROUP BY
a.s_id
) suma
ORDER BY
rk ASC
结果如下:文章来源地址https://www.toymoban.com/news/detail-736033.html
到了这里,关于sql-50练习题16-20的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!