牛客SQL.1.34

「这是我参与11月更文挑战的第17天,活动详情查看:2021最后一次更文挑战

描述

题目: 现在运营想要了解复旦大学的每个用户在8月份练习的总题目数和回答正确的题目数情况,请取出相应明细数据,对于在8月份没有练习过的用户,答题数结果返回0.

示例:用户信息表user_profile

img

img

根据示例,你的查询应返回以下结果:

img

示例1

drop table if exists `user_profile`;
drop table if  exists `question_practice_detail`;
drop table if  exists `question_detail`;
CREATE TABLE `user_profile` (
`id` int NOT NULL,
`device_id` int NOT NULL,
`gender` varchar(14) NOT NULL,
`age` int ,
`university` varchar(32) NOT NULL,
`gpa` float,
`active_days_within_30` int ,
`question_cnt` int ,
`answer_cnt` int 
);
CREATE TABLE `question_practice_detail` (
`id` int NOT NULL,
`device_id` int NOT NULL,
`question_id`int NOT NULL,
`result` varchar(32) NOT NULL,
`date` date NOT NULL
);
CREATE TABLE `question_detail` (
`id` int NOT NULL,
`question_id`int NOT NULL,
`difficult_level` varchar(32) NOT NULL
);
​
INSERT INTO user_profile VALUES(1,2138,'male',21,'北京大学',3.4,7,2,12);
INSERT INTO user_profile VALUES(2,3214,'male',null,'复旦大学',4.0,15,5,25);
INSERT INTO user_profile VALUES(3,6543,'female',20,'北京大学',3.2,12,3,30);
...
INSERT INTO question_practice_detail VALUES(1,2138,111,'wrong','2021-05-03');
INSERT INTO question_practice_detail VALUES(2,3214,112,'wrong','2021-05-09');
INSERT INTO question_practice_detail VALUES(3,3214,113,'wrong','2021-06-15');
...
INSERT INTO question_detail VALUES(1,111,'hard');
INSERT INTO question_detail VALUES(2,112,'medium');
INSERT INTO question_detail VALUES(3,113,'easy');
复制代码
3214|复旦大学|3|0
4321|复旦大学|0|0
复制代码

方法一

根据题意,没有联系过的用户也得返回答题数为0,因此考虑就两表进行外连接;由于只查询复旦大学的学生,所以对于大学的限定条件应该加上where后,再将两表进行连接时,on的条件是两个表中的两条记录分别得id相同,先做题情况表中的日期得限定在八月份;如此两张表左外连接后,统计做题数用count(question_id),这样当有学生没有做题question_id为空时,不会统计NULL值;做对的数量,是对result字段进行判断,如果是right则为1,用sum来求和;最后用id来进行分组,对每一个学生分别求得做题数和做对数;

select a.device_id, university, count(question_id) as question_cnt, sum(if(result='right', 1, 0)) as right_question_cnt
from user_profile a left join question_practice_detail b on a.device_id=b.device_id and month(b.date)=8
where university='复旦大学'
group by device_id;
复制代码

猜你喜欢

转载自juejin.im/post/7031737182020861989