如何用一个请求计算一个玩家的多个等级?

nwwlzxa7  于 2021-08-09  发布在  Java
关注(0)|答案(2)|浏览(515)

我使用的是postgresql,我想从一个表中得到所有玩家等级的列表。
例如,我有一个表“scores”:(组合user\u id-battlefield\u id在此表中是唯一的)

+----------+----------------+-------+
| user_id  | battlefield_id | score |
+==========+================+=======+
| Legolas  | Helm's Deep    | 42    |
+----------+----------------+-------+
| Legolas  | Pelennor       | 100   |
+----------+----------------+-------+
| Gimli    | Helm's Deep    | 43    |
+----------+----------------+-------+
| Gimli    | Pelennor       | 120   |
+----------+----------------+-------+
| Aragorn  | Helm's Deep    | 50    |
+----------+----------------+-------+
| Aragorn  | Pelennor       | 10    |
+----------+----------------+-------+

我想请求计算阿拉贡在任何战场上的所有军衔并返回这样的结果:

+------+----------------+
| rank | battlefield_id |
+======+================+
| 1    | Helm's Deep    |
+------+----------------+
| 3    | Pelennor       |
+------+----------------+

我目前有一个工作正常的请求,但我必须同时指定用户和战场:

SELECT count(*)+1 AS rank FROM scores WHERE score < 
(
    SELECT score FROM scores WHERE user_id = 'Aragorn' AND battlefield_id = "Pelennor"
)
AND battlefield_id = "Pelennor"

但我不知道如何适应这种情况,在任何战场上获得军衔。我不需要管理领带。

iyfamqjs

iyfamqjs1#

你可以使用窗口功能 row_number ,这是演示

select
    rnk,
    battlefield_id
from
(

  SELECT
    user_id,
    battlefield_id,
    row_number() over (partition by battlefield_id order by score desc) as rnk 
  FROM scores 
) val
where user_id = 'Aragorn'

输出:

| rnk | battlefield_id |
| --- | -------------- |
| 1   | Helm's Deep    |
| 3   | Pelennor       |
rekjcdws

rekjcdws2#

您可以将您的版本与相关子查询一起使用:

SELECT s.battlefield_id, count(*) AS rank
FROM scores s
WHERE s.score <= (SELECT s2.score
                  FROM scores s2
                  WHERE s2.user_id = 'Aragorn' AND
                        s2.battlefield_id = s.battlefield_id
                 )
GROUP BY s.battlefield_id;

这可以利用上的索引 scores(user_id, battlefield_id) . 在大量的数据上,比较一下这个和 row_number() 版本。这可能有性能优势。

相关问题