牛客网的mysql配置(我不知道是不是其他的也这样),聚合函数sum,avg,max,min这些都是不能用在where筛选的。

在这题中,我想用max(rk)-1 找到排名倒二的分数,但是where不能用,having虽然语法上不报错,但是group聚合以后,比如group by difficilty having a.rk<max(a.rk), 这里首先之前已经用where 筛选出hard,其次这里的having是用来筛选difficulty的,不是筛选a.rk的,再次,group by后面要有所有select的内容,不然就会语法报错的。总结一下就是语法和理解整个都错了。

不要用where。。。and where。。。

自己做的最接近的答案:假设知道剔除null值的score一共有五个,则下面代码能通过
select tag
, difficulty
, round(avg(score),1) as clip_avg_score
from(
select tag
, difficulty
, score
, rank()over(partition by er.exam_id order by score) as rk
from examination_info ei
inner join exam_record er
on ei.exam_id = er.exam_id
where difficulty = 'hard'
and tag = 'SQL'
and score is not null
    ) as a
    where a.rk >=2
    and a.rk<=4
    group by tag, difficulty



知识点:rank函数,这里score有空值,则排序的时候默认为最小