mysql - 如何使用 max 函数重写此“组函数的无效使用”查询以查找排名
问题描述
我有一个这样的查询,给出分数和排行榜首字母:
select MAX(score) as score, leaderboard_initials
from players p, games g where p.google_id = g.google_id
group by p.google_id
order by MAX(score) DESC;
Players
有一个主键google_id
,它是 中的外键games
。
有用。
我需要显示玩家的排名,其中考虑到他们的最高得分游戏。
我在想,对于排名,我需要 1 + 该玩家之上的玩家数量。因此,该玩家的最高得分高于该玩家。因此,我尝试了以下但得到错误invalid use of group function
:
select 1+(SELECT count(DISTINCT p2.google_id) from players p2, games
g2 where MAX(g2.score) > score) as rank,
MAX(score) as score, leaderboard_initials
from players p, games g where p.google_id = g.google_id
group by p.google_id
order by MAX(score) DESC;
我知道我不能MAX()
在 a中使用,WHERE
但我不知道如何在不这样做的情况下获得排名。有任何想法吗?
解决方案
尝试这样的事情:
SELECT p.google_id, p.leaderboard_initials, bestScores.maxScore
, COUNT(DISTINCT others.google_id) + 1 AS playerRank
FROM (
SELECT google_id, MAX(score) AS maxScore
FROM games
GROUP BY google_id
) AS bestScores
INNER JOIN players AS p
ON bestScores.google_id = p.google_id
LEFT JOIN games AS others
ON bestScores.google_id <> others.google_id
AND bestScores.maxScore < others.score
GROUP BY p.google_id, p.leaderboard_initials, bestScores.maxScore;
- 它首先找到每个玩家的最佳分数(子查询),
- 然后获取玩家信息(INNER JOIN 玩家),
- 然后得到其他玩家的所有更好的分数(LEFT JOIN games as others)
- 最后它计算得分更高的不同玩家的数量
推荐阅读
- delphi - 在 TContourSeries 中未触发 OnGetMarkText
- android - Android 键盘覆盖视图,但仅在全屏模式下
- sparql - 如何在 SPARQL 中执行“过滤器(x IN(...))”?
- symfony - Symfony 如何使用 SonataAdmin 更改用户密码?
- sql - SQL:按选定列对记录进行分组
- typescript - 打字稿节点找不到模块
- ios - 在静态函数闭包上更改 UIButton 属性
- android - 无法解决android中的flutter firestore
- mysql - 如何模拟mysql数据库?
- sql-server - SSIS 表达式生成器从年份返回 YY