题76:
根据下表:写一段 SQL 语句,查询出每个学生参加每一门科目测试的次数,结果按 student_id 和 subject_name 排序。
其中:
- Students表:主键为 student_id(学生ID),该表内的每一行都记录有学校一名学生的信息;
- Subjects表:主键为 subject_name(科目名称),每一行记录学校的一门科目名称;
- Examinations表:无主键,可能存在重复行;学生表里的一个学生修读科目表里的每一门科目,而这张考试表的每一行记录就表示学生表里的某个学生参加了一次科目表里某门科目的测试。
解题思路:
(1)现将Students表和Subjects表求笛卡尔积,得到一个新表;
(2)然后再左连接Examinations表;
(3)根据需要查询想要的字段;
(4)注意的是这里不能用COUNT(*),要用COUNT(c.subject_name),因为e.subject_name中才有NULL。
select a.student_id ,a.student_name ,b.subject_name,count(c.subject_name) attended_exams
from Students a
cross join Subjects b
left join Examinations c
on a.student_id = c.student_id and b.subject_name = c.subject_name
group by a.student_id , b.subject_name
order by a.student_id , b.subject_name ;