user_id | name | score |
1 | john | 1000 |
2 | mike | 1200 |
3 | jelly | 1300 |
4 | brook | 1500 |
5 | nanny | 1200 |
需要知道 user_id = k 的用户对应的积分排名
SELECT user_id, name, score, RANK() OVER (ORDER BY score DESC) FROM user;
user_id | name | score | rank |
4 | brook | 1500 | 1 |
3 | jelly | 1200 | 2 |
2 | mike | 1300 | 3 |
5 | nanny | 1500 | 3 |
1 | john | 1200 | 5 |
如要获取排名 3 的用户:
SELECT user_id, name, score, user_rank FROM (SELECT user_id, name, score, RANK() OVER (ORDER BY score DESC) AS user_rank FROM user) AS T WHERE user_rank 3;
-- 注意子查询在from中需要写别名
user_id | name | score | rank |
4 | brook | 1500 | 1 |
3 | jelly | 1200 | 2 |
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。如有错误或未考虑完全的地方,望不吝赐教。