mysql - 排名排行榜 - MySQL
问题描述
我有一张这样的桌子
+-----+-------+
| pid | score |
+-----+-------+
| 1 | 120|
| 2 | 130|
| 3 | 100|
| 1 | 120|
| 2 | 130|
| 3 | 100|
+-----+-------+
我试图让我的用户排名。目前我正在使用这个查询,
SELECT pid
, SUM(score) AS total_score
FROM score
GROUP
BY pid
ORDER
BY total_score DESC
我通过这个查询得到一个按分数排序的列表,但没有得到他们的位置。我想要这样的东西
+-----+-------+------+
| pid | score | rank |
+-----+-------+------+
| 2 | 260| 1 |
| 1 | 240| 2 |
| 3 | 200| 3 |
+-----+-------+------+
我可以为特定用户获得这个职位吗?喜欢
+-----+-------+------+
| pid | score | rank |
+-----+-------+------+
| 1 | 240| 2 |
+-----+-------+------+
我正在使用 MySQL 5.7.21。你能帮忙吗?
解决方案
如果你有机会使用 Mysql 8.0.2 或更高版本,你就有了函数排名。
否则您可以使用变量来设置排名:
SELECT pid,
total_score,
@curRank := @curRank + 1 AS rank
FROM
(SELECT pid,
sum(score) AS total_score
FROM score
GROUP BY pid
ORDER BY total_score DESC) datas, (SELECT @curRank := 0) r
您可以过滤后仅获得所需 pid 的结果
推荐阅读
- c# - 在 List 上实现排序算法
- entity-framework - 在 DBFirst 场景中,在映射中添加 .HasIndex() 有什么好处?
- jasper-reports - 如何用一条线覆盖所有的细节空间
- ios - 归档 iOS 应用程序时出错 - “通用专业化”
Swift.String.init 的" - activemq - 如何使我的上次映像恢复策略主题在代理重新启动后仍然存在?
- docker - 如何更正makefile中的docker,它需要至少1个参数来删除所有容器命令
- sharepoint-online - 使用作者/电子邮件使用 SharePoint REST API 进行查询
- javascript - JS Canvas 游戏使用按键事件来修改按住 shift 按钮时的速度
- php - 如何在 Laravel 中创建用户和帖子之间的关系
- r - 尝试在 R 中绘制复杂函数时出现错误消息