Cesar
Cesar

Reputation: 717

Get user ranks in multiple leaderboard

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:

for user 2:

for user 3:

I have been working with SQL for a while, but this is becoming a little complex.

Upvotes: 2

Views: 956

Answers (1)

Juan Carlos Oropeza
Juan Carlos Oropeza

Reputation: 48207

SQL DEMO

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

enter image description here

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

Related Questions