
牛客网题目:表user_profile,查看每个学校用户的平均发贴和回帖情况,寻找低活跃度学校进行重点运营,请取出平均发贴数低于5的学校或平均回帖数小于20的学校。

如果用where,则需要用到子查询语句:
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 t
where t.avg_question_cnt<5 or t.avg_answer_cnt<20
如果想用聚合函数结果 avg(question_cnt)<5 or avg(answer_cnt)<20作为筛选条件,则不能用where,而是用having语句。
错误:
select university,avg(question_cnt) as avg_question_cnt,avg(answer_cnt) as avg_answer_cnt
from user_profile
group by university
where avg(question_cnt)<5 or avg(answer_cnt)<20
正确:
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 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
本文通过牛客网的一道题目,解释了在SQL查询中,当聚合函数如avg用于筛选条件时,应当使用having而非where子句。错误示例展示了直接在where子句中使用聚合函数会导致语法错误,而正确的做法是在having子句中进行条件判断,以获取平均发贴数低于5或平均回帖数小于20的学校信息。

被折叠的 条评论
为什么被折叠?



