继续刷牛客题,记录一些知识点
1.查选最高和最低结果 关键字order by和limit max
select gpa form user_profile where university='复旦大学' order by gpa desc limit 1
select max(gpa) as gap from user_profile where university ='复旦大学'
2.统计个数 关键字 count 四舍五入 count
round是四舍五入,round中的1表示保留一位小数。由于是要求男性,所以where使用gender=male来加以限制。再来count用来计数。
select
count(gender) as male_num,
round(avg(gpa), 1) as avg_gpa
from
user_profile
where
gender = 'male'
3.分组计算 关键字group by
题目解析:计算每个学校和每种性别 :使用group by,计算用户数 count ,30天天内平均活跃天数 avg函数,平均发帖数 avg
select
gender,
university,
count(device_id) as user_num,
avg(active_days_within_30) as avg_active_day,
avg(question_cnt) as avg_question_cnt
from
user_profile
group by
gender,
university
其中涉及到正确的排序顺序:from(组装来自不同数据源的数据),再到where(基于指定条件,对数据进行筛选排序)再用group by (将筛选后的数据划分成多个分组),having ,最后是select。
首先确定数据来自哪张表,然后按where条件对数据进行筛选,然后才能进行group by分组(分组条件可以有多个,按字段顺序依次分组),分组之后由having对结果进行过滤把数据呈现出来。
4.分组过滤 关键字group by 和 having
select
university,
avg(question_cnt) as avg_question_cnt,
avg(answer_cnt) as avg_answer_cnt
from
user_profile
group by
university
having
avg_question_cnt < 5
or avg_answer_cnt< 20
为什么不用where来做条件筛选,因为是聚合函数结果作为筛选条件,不能用where,而是用having语法,配合重新命名即可。having通常和group by函数使用。
5.分组排序 关键字group by 和order by
select
university,
avg(question_cnt) as avg_question_cnt
from
user_profile
group by
university
order by
avg_question_cnt ASC
首先从user_profile选择,再执行group by university,再执行select, 最后执行order by再进行排序。