题解 | 分组过滤练习题
分组过滤练习题
https://www.nowcoder.com/practice/ddbcedcd9600403296038ee44a172f2d
--- 方法一:使用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
--- 方法二:使用子查询表进行二次过滤
select *
from (
select university,AVG(question_cnt) as avg_question_cnt,AVG(answer_cnt) as avg_answer_cnt
from user_profile
group by university
) as t1
where t1.avg_question_cnt < 5 or t1.avg_answer_cnt < 20;
方法一:复习一下sql子句的执行顺序
- where子句
- group by
- having,最group by 进行过滤,可以使用聚合函数,但是不能对聚合后的列字段起别名
- select,此处可以使用聚合函数,可以起别名
- order by,最后进行一个排列,很符合逻辑
- limit,有时用到
方法二:不必多言,子查询
唯一需要多说的可能就是子查询也返回一个临时表,这个表可以起一个别名用于外表查询中的调用

查看11道真题和解析