我正在开发一个带有 rails 和 postgres 的网络应用作为射击场游戏后端。它有一个终点来保存玩家得分,它将得分写入DB并返回前三个位置和玩家'围绕着它的一些背景排列:前一个地方和后一个地方。例如,如果玩家具有等级23,则该方法应返回第1,第2,第3位,玩家等级本身以及除了它之外的等级22和24的两个记录。我不会使用以下 sql 查询动态计算数据库中的排名:
SELECT RANK() OVER(ORDER BY score DESC) AS place, name, score
FROM scores
WHERE game_id=? AND rules_version=? AND game_mode=?
LIMIT 10
POST
请求以下数据:
{
"players": [
{ "name": "Jack", "score": 100, "local_id": 1, "stats": {}},
{ "name": "Anna", "score": 200, "local_id": 2, "stats": {}}
]
}
应返回以下结果集:
{
"scores": [
{
"name": "Piter",
"place": 1,
"score": 800
},
{
"name": "Lisa",
"place": 2,
"score": 700
},
{
"name": "Philip",
"place": 3,
"score": 600
},
{
"name": "Max",
"place": 25,
"score": 204
},
{
"name": "Anna",
"place": 26,
"score": 200,
"local_id": 2
},
{
"name": "Ashley",
"place": 27,
"score": 193
}
{
"name": "Norman",
"place": 36,
"score": 103
},
{
"name": "Jack",
"place": 37,
"score": 100,
"local_id": 1
},
{
"name": "Chris",
"place": 38,
"score": 95
}
]
}
除了local_id
之外的每个字段以及我所说的place
都存储在DB中。我无法找出正确的sql查询来做这样的选择。请帮忙。