数据准备
Create table If Not Exists Students (student_id int, student_name varchar(20));
Create table If Not Exists Subjects (subject_name varchar(20));
Create table If Not Exists Examinations (student_id int, subject_name varchar(20));
Truncate table Students;
insert into Students (student_id, student_name) values ('1', 'Alice');
insert into Students (student_id, student_name) values ('2', 'Bob');
insert into Students (student_id, student_name) values ('13', 'John');
insert into Students (student_id, student_name) values ('6', 'Alex');
Truncate table Subjects;
insert into Subjects (subject_name) values ('Math');
insert into Subjects (subject_name) values ('Physics');
insert into Subjects (subject_name) values ('Programming');
Truncate table Examinations;
insert into Examinations (student_id, subject_name) values ('1', 'Math');
insert into Examinations (student_id, subject_name) values ('1', 'Physics');
insert into Examinations (student_id, subject_name) values ('1', 'Programming');
insert into Examinations (student_id, subject_name) values ('2', 'Programming');
insert into Examinations (student_id, subject_name) values ('1', 'Physics');
insert into Examinations (student_id, subject_name) values ('1', 'Math');
insert into Examinations (student_id, subject_name) values ('13', 'Math');
insert into Examinations (student_id, subject_name) values ('13', 'Programming');
insert into Examinations (student_id, subject_name) values ('13', 'Physics');
insert into Examinations (student_id, subject_name) values ('2', 'Math');
insert into Examinations (student_id, subject_name) values ('1', 'Math');
需求
要求写一段 SQL 语句,查询出每个学生参加每一门科目测试的次数,结果按 student_id 和 subject_name 排序。
输入
输出
- 三表联查,学生表和学科表使用笛卡尔积,之后用左外和考试表连接
-- 三表联查,学生表和学科表使用笛卡尔积,之后用左外和考试表连接
-- 关联条件: 学生表id=考试表id and 学科表name=考试表name
select *
from Students s cross join Subjects sub
left join Examinations e
on s.student_id=e.student_id and sub.subject_name=e.subject_name;
2. 以学生id,学生姓名,学科名字分组,并使用count(eid)求出每个科目考试的次数
-- 以学生id,学生姓名,学科名字分组,并使用count(eid)求出每个科目考试的次数
-- eid为与考试表关联之后得到的id,如果没有参见考试,则id为空,后期count时,不计算,则可以求出每个科目参加考试的次数
with t1 as (
select s.student_id,student_name,sub.subject_name,e.student_id eid
from Students s cross join Subjects sub
left join Examinations e
on s.student_id=e.student_id and sub.subject_name=e.subject_name
)
select student_id,student_name,subject_name,
count(eid) as attended_exams
from t1
group by student_id,student_name,subject_name
order by student_id,subject_name;