牛客SQL.1.28

305 阅读2分钟

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

描述

题目:现在运营想要计算出2021年8月每天用户练习题目的数量,请取出相应数据。

示例:question_practice_detail

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(4,115,'easy');
INSERT INTO question_detail VALUES(5,116,'medium');
INSERT INTO question_detail VALUES(6,117,'easy');
13|5
14|2
15|3
16|1
18|1

方法一

根据题意,我们需要统计出在2021年8月有做题记录的某天里所有用户在当天的做题数量;首先根据日期来分组,获得每组的记录数即为当天所有用户的做题数,在利用WHERE语句来限定年月,获得指定日期的结果;SQL语句如下:

SELECT DAY(date) AS day, COUNT(*) AS question_cnt
FROM question_practice_detail
WHERE MONTH(date)=8 AND YEAR(date)=2021
GROUP BY date;

这里用函数DAYMONTHYEAR来获取date中对应的值;

运行效果

image-20211113152523867

从上图看出,输入的语句最终变为了如下:

SELECT DAYOFMONTH(date) AS day, COUNT(0) AS question_cnt
FROM question_practice_detail
WHERE MONTH(date)=8 AND YEAR(date)=2021
GROUP BY date;

image-20211113153903546

对于表的访问采用的是全表扫描的方式,开销为4.2,并且使用了临时表,用于排序的开销为16,该计划总共的开销为两者相加20.2;