题解 | #每类试卷得分前3名#

每类试卷得分前3名

https://www.nowcoder.com/practice/255aa1863fe14aa88694c09ebbc1dbca

# 构造临时表1:链接exam_id
with table1 as(
    select uid,tag,score
    from exam_record left join examination_info using(exam_id)
    where score is not null
),
# 构造表2:按照tag进行分组,组内按照分数倒序
# 注意点:比较最大分,再比较最小分,最后比较uid,直接在order中实现
table2 as(
    select tag,uid,max(score),min(score),
    row_number()over(partition by tag order by max(score) desc ,min(score) desc,uid desc) as ranking
    from table1
    group by tag,uid
)
# 注意点:row_number中使用了聚合函数max\min,表示对同一个tag、同一个uid下面进行排序。按照tag/uid分组(即对select中没有聚合的字段进行group by)
# 注意点:窗口函数的执行顺序是在group by之后的,所以他是对最后的结果进行再计算
select tag,uid,ranking
from table2 
where ranking <=3

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务