题解 | #考试分数(三)#

考试分数(三)

https://www.nowcoder.com/practice/b83f8b0e7e934d95a56c24f047260d91

SELECT a.id,l.name,a.score
FROM
    language AS l
    JOIN (
        SELECT id,language_id,score,
            dense_rank() over (PARTITION BY language_id ORDER BY score DESC
            ) AS rank_num
        FROM grade
    ) a ON l.id = a.language_id
WHERE rank_num <= 2
ORDER BY l.name,a.score DESC,a.id;

首先用dense_rank()给每个岗位进行排序。注意这里排序不用跳过位次,故使用dense_rank。

注:跳过位次使用rank,每个位次唯一使用row_number

 dense_rank() over (PARTITION BY language_id ORDER BY score DESC) AS rank_num

在取出位次前两位

WHERE rank_num <= 2

排序

ORDER BY l.name,a.score DESC,a.id;

完整代码如下

SELECT a.id,l.name,a.score
FROM
    language AS l
    JOIN (
        SELECT id,language_id,score,
            dense_rank() over (PARTITION BY language_id ORDER BY score DESC
            ) AS rank_num
        FROM grade
    ) a ON l.id = a.language_id
WHERE rank_num <= 2
ORDER BY l.name,a.score DESC,a.id;

全部评论

相关推荐

我见java多妩媚:大外包
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务