第十八例:分组计算练习题
- 题目地址:分组计算练习题牛客题霸牛客网 (nowcoder.com)
- 初始化数据:
droptable if exists user_profile;
CREATETABLE `user_profile` (
`id` intNOTNULL,
`device_id` intNOTNULL,
`gender` varchar(14) NOTNULL,
`age` int ,
`university` varchar(32) NOTNULL,
`gpa` float,
`active_days_within_30` float,
`question_cnt` float,
`answer_cnt` float
);
INSERTINTO user_profile VALUES(1,2138,'male',21,'北京大学',3.4,7,2,12);
INSERTINTO user_profile VALUES(2,3214,'male',null,'复旦大学',4.0,15,5,25);
INSERTINTO user_profile VALUES(3,6543,'female',20,'北京大学',3.2,12,3,30);
INSERTINTO user_profile VALUES(4,2315,'female',23,'浙江大学',3.6,5,1,2);
INSERTINTO user_profile VALUES(5,5432,'male',25,'山东大学',3.8,20,15,70);
INSERTINTO user_profile VALUES(6,2131,'male',28,'山东大学',3.3,15,7,13);
INSERTINTO user_profile VALUES(7,4321,'male',28,'复旦大学',3.6,9,6,52);
- 题目描述:想要对美国个学校不同性别的用户活跃情况和发帖数量进行分析,请分别计算出每个学校每种性别的用户数,30天内平均活跃天数和平均发帖数量
- 分析1:分别统计性别用户数,再统计平均活跃天数和发帖数量使用group by进行分组:
select
gender,
university,
count(device_id) as user_num,
round(avg(active_days_within_30),1) as avg_active_day,
round(avg(question_cnt),1) as avg_question_cnt
from
user_profile
groupby
gender,
university
第十九例:分组查询,分组过滤练习题
- 题目链接:分组过滤练习题牛客题霸牛客网 (nowcoder.com)
- 初始化数据:
droptable if exists user_profile;
CREATETABLE `user_profile` (
`id` intNOTNULL,
`device_id` intNOTNULL,
`gender` varchar(14) NOTNULL,
`age` int ,
`university` varchar(32) NOTNULL,
`gpa` float,
`active_days_within_30` int ,
`question_cnt` float,
`answer_cnt` float
);
INSERTINTO user_profile VALUES(1,2138,'male',21,'北京大学',3.4,7,2,12);
INSERTINTO user_profile VALUES(2,3214,'male',null,'复旦大学',4.0,15,5,25);
INSERTINTO user_profile VALUES(3,6543,'female',20,'北京大学',3.2,12,3,30);
INSERTINTO user_profile VALUES(4,2315,'female',23,'浙江大学',3.6,5,1,2);
INSERTINTO user_profile VALUES(5,5432,'male',25,'山东大学',3.8,20,15,70);
INSERTINTO user_profile VALUES(6,2131,'male',28,'山东大学',3.3,15,7,13);
INSERTINTO user_profile VALUES(7,4321,'male',28,'复旦大学',3.6,9,6,52);
- 题目描述:查看每个学校用户的平均发帖和回帖情况,寻找活跃度进行重点运营,请取出平均发帖数低于5的学校或平均回帖数小于20的学校
- 分析1:要统计每个学校平均发帖和回帖情况:select university,round(avg(question_cnt),1) as avg_question_cnt, roung(avg(answer_cnt),1) as avg_answer_cnt from user_profile;
- 分析2:平均发帖数低于5和回帖数小于20的需要使用having过滤:select
university,
round(avg(question_cnt),3) as avg_question_cnt,round(avg(answer_cnt),3) as avg_answer_cnt
from user_profile group by university having avg_question_cnt < 5 or avg_answer_cnt < 20; - 代码示例 :
select
university,
round(avg(question_cnt),3) as avg_question_cnt,
round(avg(answer_cnt),3) as avg_answer_cnt
from
user_profile
groupby
university
having
avg_question_cnt < 5
or avg_answer_cnt < 20;