SQL server怎么查询每个班级每个科目的前三名
时间: 2023-05-27 18:01:56 浏览: 104
假设有关联的表格如下:
class (班级表)
----------
class_id (班级编号)
class_name (班级名称)
subject (科目表)
----------
subject_id (科目编号)
subject_name (科目名称)
student (学生表)
----------
student_id (学生编号)
class_id (班级编号)
student_name (学生姓名)
score (分数表)
----------
score_id (分数编号)
subject_id (科目编号)
student_id (学生编号)
score (分数)
可以使用如下SQL查询语句来查询每个班级每个科目的前三名:
SELECT s.class_name, sb.subject_name, st.student_name, sc.score
FROM class s
INNER JOIN student st ON s.class_id = st.class_id
INNER JOIN score sc ON st.student_id = sc.student_id
INNER JOIN subject sb ON sc.subject_id = sb.subject_id
WHERE (SELECT COUNT(*) FROM score sc2 WHERE sc2.subject_id = sc.subject_id AND sc2.student_id = sc.student_id AND sc2.score >= sc.score) <= 3
ORDER BY sc.subject_id, sc.score DESC;
解释:
1. 在内部查询中,COUNT(*)函数计算出每个学生在同一科目中的成绩排名。
2. 外部查询用INNER JOIN连接4个表,同时将内部查询放入WHERE子句以显示前三名。
3. ORDER BY 子句按科目和成绩的降序排序,因此每个班级每个科目可显示前三名。
阅读全文