Reputation: 717
I am using Sequelize and I have a table in this way:
+--------+-------------+--------+
| userId | leaderboard | points |
+--------+-------------+--------+
| 1 | lead1 | 10 |
| 1 | lead2 | 20 |
| 1 | lead1 | 5 |
| 2 | lead2 | 10 |
| 2 | lead1 | 10 |
| 2 | lead1 | 15 |
| 3 | lead2 | 15 |
+--------+-------------+--------+
I have been using rank() for creating a ranking of who user has more points, or who users has more points for a given leaderboard (lead1 or lead2), but now I need to find the current rank of a user in the different leaderboards (in the example table are two but can be n), So, I need something like:
for user 1:
user 1 - lead1 - 15 points - rank 2
user 1 - lead2 - 20 points - rank 1
for user 2:
user 2 - lead1 - 25 points - rank 1
user 2 - lead2 - 10 points - rank 3
for user 3:
I have been working with SQL for a while, but this is becoming a little complex.
Upvotes: 2
Views: 956
Reputation: 48207
WITH total_points as (
SELECT "userId", "leaderboard", SUM("points") as "points"
FROM Table1
GROUP BY "userId", "leaderboard"
)
SELECT "userId", "leaderboard", "points",
RANK() OVER (PARTITION BY "leaderboard" ORDER BY "points" DESC) as ranking
FROM total_points
ORDER BY "userId", "leaderboard"
OUTPUT
Remember you have RANK()
and DENSE_RANK()
https://blog.jooq.org/2014/08/12/the-difference-between-row_number-rank-and-dense_rank/
Upvotes: 4