跳到主要内容

1280.学生们参加各科测试的次数

序号题目难度
1280题目链接简单

题目大意​

查询出每个学生参加每一门科目测试的次数,结果按 student_id 和 subject_name 排序。

学生表: Students

Column NameType
student_idint
student_namevarchar

在 SQL 中,主键为 student_id(学生ID)。 该表内的每一行都记录有学校一名学生的信息。

科目表: Subjects

Column NameType
subject_namevarchar

在 SQL 中,主键为 subject_name(科目名称)。 每一行记录学校的一门科目名称。

考试表: Examinations

Column NameType
student_idint
subject_namevarchar

这个表可能包含重复数据(换句话说,在 SQL 中,这个表没有主键)。 学生表里的一个学生修读科目表里的每一门科目。 这张考试表的每一行记录就表示学生表里的某个学生参加了一次科目表里某门科目的测试。

示例​

输入​

Students table:

student_idstudent_name
1Alice
2Bob
13John
6Alex

Subjects table:

subject_name
Math
Physics
Programming

Examinations table:

student_idsubject_name
1Math
1Physics
1Programming
2Programming
1Physics
1Math
13Math
13Programming
13Physics
2Math
1Math

输出​

student_idstudent_namesubject_nameattended_exams
1AliceMath3
1AlicePhysics2
1AliceProgramming1
2BobMath1
2BobPhysics0
2BobProgramming1
6AlexMath0
6AlexPhysics0
6AlexProgramming0
13JohnMath1
13JohnPhysics1
13JohnProgramming1

解释​

结果表需包含所有学生和所有科目(即便测试次数为0): Alice 参加了 3 次数学测试, 2 次物理测试,以及 1 次编程测试; Bob 参加了 1 次数学测试, 1 次编程测试,没有参加物理测试; Alex 啥测试都没参加; John 参加了数学、物理、编程测试各 1 次。

参考答案​

select
t1.student_id
,t1.student_name
,t3.subject_name
,sum(case when t2.subject_name is not null then 1 else 0 end) as attended_exams
from Students t1
join Subjects t3
on 1=1
left join Examinations t2
on t1.student_id = t2.student_id
and t2.subject_name = t3.subject_name
group by 1,2,3
order by 1,3
;