0

What is the most efficient SQL query for leaderboards if we have table:

[UserID], [Points]

I would like to have the result be sorted by Points and with Rank column.

Andrei
  • 42,814
  • 35
  • 154
  • 218
  • 4
    You tagged this with MySQL and SQL Server. Please specify the RDBMS that you are targeting by adding the appropriate tag (Oracle, SQL Server, MySQL, etc.). There may be answers that take advantage of language or product features that are not universally supported. Also, by tagging it with a specific RDBMS, your question may receive attention from people better suited to answer it. – Taryn Apr 19 '13 at 12:54

3 Answers3

2

In SQL Server 2008, you can use the Ranking functions:

SELECT UserId,
       Points,
       RANK() OVER(ORDER BY Points DESC) AS Rank
FROM LeaderBoards
ORDER BY Points DESC

A MySql rank could be something like this:

SELECT UserId,
       Points,
       @curRank := @curRank + 1 AS Rank
FROM LeaderBoards l, (SELECT @curRank := 0) r
ORDER BY Points DESC
Community
  • 1
  • 1
Cyril Gandon
  • 16,830
  • 14
  • 78
  • 122
1

The query should be:

SELECT UserID, Points FROM table ORDER BY Points

Generating a rank column is probably easier in whatever display technology you're using, ie, php, etc. It can be done in most flavors of SQL but the syntax will vary.

  • Thanks, in fact, with Nenad Zivkovic's query I will get Rank column which is absolutely what I need – Andrei Apr 19 '13 at 13:02
0

Here is a solution that takes advantage of join:

SELECT t1.UserID, t1.Points, COUNT(t2.Points) AS Rank
FROM LeaderBoards t1
JOIN LeaderBoards t2 ON t1.Points < t2.Points OR (t1.Points=t2.Points and t1.UserID = t2.UserID)
GROUP BY t1.UserID, t1.Points
ORDER BY t1.Points DESC, t1.UserID DESC;

I tested this on MySQL. For a more detailed article on this please see: http://www.artfulsoftware.com/infotree/qrytip.php?id=460

Todd Palmer
  • 1,002
  • 10
  • 20