SQL 经典题型解答(完)
SQL 经典习题解答(7)
35、查询所有学生的课程及分数情况;
SELECT
a.*,
b.c,
c.cname,
b.score
FROM
student a,
sc b,
course c
WHERE
a.s = b.S
AND b.c = c.C
程序运行结果:
36、查询任何一门课程成绩在70分以上的姓名、课程名称和分数
SELECT
a.sname,
b.cname,
c.score
FROM
student a,
course b,
sc c
WHERE
a.s = c.S
AND b.c = c.c
AND c.score > 70
程序运行结果:
37、查询不及格的课程
SELECT
a.s,
a.sname,
b.cname,
c.score
FROM
student a,
course b,
sc c
WHERE
a.s = c.S
AND b.c = c.c
AND c.score < 60
程序运行结果:
38、查询课程编号为01且课程成绩在80分以上的学生的学号和姓名
SELECT
a.s,
a.sname
FROM
student a,
sc b
WHERE
a.s = b.s
AND b.c = '01'
AND b.score > 80
程序运行结果:
39、求每门课程的学生人数
SELECT DISTINCT
b.Cname,
COUNT( a.c ) OVER ( PARTITION BY a.C ) AS num
FROM
sc a
INNER JOIN course b ON a.c = b.C
详情:
COUNT( a.c ) OVER ( PARTITION BY a.C ) AS num
用于计算每门课程的学习人数,再与表 course 连接得到课程名称,在选择时加上DISTINCT
。
程序运行结果:
40、查询选修"张三"老师所授课程的学生中,成绩最高的学生信息及其成绩
SELECT
a.*,
b.score
FROM
student a,
sc b,
course c,
teacher d
WHERE
a.s = b.s
AND b.c = c.C
AND c.T = d.T
AND d.Tname = '张三'
ORDER BY
score DESC
LIMIT 1
详解:
用到
SELECT TOP
语句,用于规定要返回的记录的数目。
SELECT TOP
用法
程序运行结果:
41、查询不同课程成绩相同的学生的学生编号、课程编号、学生成绩
SELECT
a.*
FROM
sc a,
sc b
WHERE
a.s != b.s
AND a.c != b.C
AND a.score = b.score
详解;
不是很懂这道题问的什么
程序运行结果:
42、查询每门功课成绩最好的前两名
SELECT
a.*,
b.c,
b.score,
b.mc
FROM
student a,
( SELECT *, ROW_NUMBER ( ) OVER ( PARTITION BY c ORDER BY score DESC ) AS mc FROM sc ) b
WHERE
a.s = b.s
AND b.mc < 3
详解:
首先通过表 sc 按照课程成绩对学生进行排名,在与表 student 连接得到结果
程序运行结果:
43、统计每门课程的学生选修人数(超过5人的课程才统计)。要求输出课程号和选修人数,查询结果按人数降序排列,若人数相同,按课程号升序排列
SELECT
c,
COUNT( 1 ) AS num
FROM
sc
GROUP BY
C
HAVING
COUNT( 1 ) > 5
ORDER BY
num DESC,
c
程序运行结果:
44、检索至少选修两门课程的学生学号
SELECT
s
FROM
sc
GROUP BY
s
HAVING
COUNT( s ) >= 2
程序运行结果:
45、查询选修了全部课程的学生信息
SELECT
a.*
FROM
student a,
( SELECT s, count( s ) AS num FROM sc GROUP BY s ) b
WHERE
a.s = b.s
AND b.num IN ( SELECT COUNT( c ) FROM course )
程序运行结果:
46、查询各学生的年龄
SELECT
s,
Sname,
EXTRACT( YEAR FROM NOW( ) ) - EXTRACT( YEAR FROM sage ) AS '年龄'
FROM
student
详解:
运用
EXTRACT
计算年龄,EXTRACT
用法
程序运行结果;
47、查询本周过生日的学生
SELECT
s,
Sname
FROM
student
WHERE
YEARWEEK( DATE_FORMAT( sage, '%Y %m %d' ) ) = YEARWEEK( NOW( ) )
详解:
YEARWEEK
用法 用于返回该时间是这一年的第几周。
DATE_FORMAT
用法 用于以不同的格式显示日期时间数据
48、查询下周过生日的学生
SELECT
s,
Sname
FROM
student
WHERE
YEARWEEK( DATE_FORMAT( sage, '%Y %m %d' ) ) = YEARWEEK( NOW( ) ) + 1
49、查询本月过生日的学生
SELECT
s,
Sname
FROM
student
WHERE
MONTH( DATE_FORMAT( sage, '%Y %m %d' ) ) = MONTH( NOW( ) )
详解:
MONTH
函数 用于返回该时间的月份
50、查询下月过生日的学生
SELECT
s,
Sname
FROM
student
WHERE
MONTH( DATE_FORMAT( sage, '%Y %m %d' ) ) = MONTH( NOW( ) ) + 1