第十四例:分组过滤练习题
- 题目地址:分组过滤练习题牛客题霸牛客网 (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);
- 法一:看懂题目要求,不过过滤分组需要使用having:
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_answer_cnt < 20or avg_question_cnt<5;
第十五例:分组排序练习题
- 题目地址:分组排序练习题牛客题霸牛客网 (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` int ,
`answer_cnt` int
);
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);
- 法一:就是基础查询:
select
university,round(avg(question_cnt),4) as avg_question_cnt
from
user_profile
groupby
university
orderby
avg_question_cnt asc;