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

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

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

查询结构格式如下所示。

LeetCode_sql_day04(1280. 学生们参加各科测试的次数)_第1张图片

数据准备:

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')

分析:

①分析要输出的表,可以将其拆成两个较简单的表v1,v2

LeetCode_sql_day04(1280. 学生们参加各科测试的次数)_第2张图片

观察v1表,发现使用笛卡尔积连接Students表,Subjects表  (可以先创建视图方便查询)

create view v1 as
select * from Students,Subjects

观察v2表,发现在Examinations表中可以大致操作一下

create view v2 as
select *,count(subject_name)cou from Examinations group by student_id,subject_name;

③观察发现两个表需要v1左连接v2,尝试连接两个表后,再进一步完善

 LeetCode_sql_day04(1280. 学生们参加各科测试的次数)_第3张图片

 ④通过与输入表对比,需要使用ifnull函数完善count,还需要进一步分组、排序

select v1.student_id, student_name, v1.subject_name,ifnull(cou,0)
from v1
         left join v2 on v1.student_id = v2.student_id and v1.subject_name = v2.subject_name
group by student_id,v1.subject_name

⑤最后用原来的查询语句替换v1,v2视图。

代码:

select v1.student_id, student_name, v1.subject_name,ifnull(cou,0)attended_exams
from (select * from Students,Subjects)v1
         left join (select *,count(subject_name)cou from Examinations group by student_id,subject_name)v2 on v1.student_id = v2.student_id and v1.subject_name = v2.subject_name
group by student_id,v1.subject_name
order by student_id,subject_name;

总结:

①两个表直接连接不加条件是笛卡尔积

②子查询

③ifnull(列名,默认) :如果列名值为空则将默认值赋给它

④可以将两个表进行拼接,把大问题化小

你可能感兴趣的:(sql,leetcode,sql,数据库)