第十二例:计算男生人数以及平均GPA
- 题目地址:查找GPA最高值牛客题霸牛客网 (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);
INSERTINTO user_profile VALUES(1,2234,'male',21,'北京大学',3.2);
INSERTINTO user_profile VALUES(2,2235,'male',null,'复旦大学',3.8);
INSERTINTO user_profile VALUES(3,2236,'female',20,'复旦大学',3.5);
INSERTINTO user_profile VALUES(4,2237,'female',23,'浙江大学',3.3);
INSERTINTO user_profile VALUES(5,2238,'male',25,'复旦大学',3.1);
INSERTINTO user_profile VALUES(6,2239,'male',25,'北京大学',3.6);
INSERTINTO user_profile VALUES(7,2240,'male',null,'清华大学',3.3);
INSERTINTO user_profile VALUES(8,2241,'female',null,'北京大学',3.7);
- 法一:先count统计出总人数然后再将总人数的gpa平均四舍五入以为小数然后检索出需要的男性:
selectcount(gender) as male_num,round(avg(gpa),1) as avg_gpa from user_profile where gender='male';
第十三例:分组计算练习题
- 题目地址:分组计算练习题牛客题霸牛客网 (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);
- 法一:没有方法,存粹就是看懂了就会做:
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;