No*.6【SQL】#1280-学生们参加各科测试的次数
前期准备创建Students,Subjects,Examinations三个表如下droptableifexistsStudents;droptableifexistsSubjects;droptableifexistsExaminations;createtableStudents(student_idint,student_namevarchar(10));createtableSubjects(subject_namevarchar(15));createtableExaminations(student_idint,subject_namevarchar(15));showtables;插入数据-- 插入 Students 表数据INSERTINTOStudents(student_id,student_name)VALUES(1,Alice),(2,Bob),(13,John),(6,Alex);-- 插入 Subjects 表数据INSERTINTOSubjects(subject_name)VALUES(Math),(Physics),(Programming);-- 插入 Examinations 表数据INSERTINTOExaminations(student_id,subject_name)VALUES(1,Math),(1,Physics),(1,Programming),(2,Programming),(1,Physics),(1,Math),(13,Math),(13,Programming),(13,Physics),(2,Math),(1,Math);具体实现实例selects.student_id,s.student_name,sub.subject_name,count(e.subject_name)asattended_examsfromStudents scrossjoinSubjects subleftjoinExaminations eons.student_ide.student_idandsub.subject_namee.subject_namegroupbys.student_id,s.student_name,sub.subject_nameorderbys.student_id,sub.subject_name;4.难点分析众所周知leetcode很多简单题都不简单这个题目我给的评价是中等题。首先我们要从输出的样例中找到解题的线索我们可以发现第一条线索就是每个student_id和student_name都占有三行说明两者构成一个笛卡尔积序列两个表刚好构成12个元素是符合题目输出的条件。有了这个作为主表之后我们可以左连接left join上Examinations得到如下图所示看到查询生成的表结构此时答案已经显而意见我们只需要计算最后一列e.subject_name的不同的值数就可以了。