Question

I'm making a leaderboard with rankings. Its using SQL to get the data. Now I'm wondering, how can I actually let it rank?

For example:

Name: Wins: Points: Skills:
Matt 1 2009 2
Mark 4 2014 8

How can I let PHP calculate what is at top and give it a rank? So that "Mark" will be at the first line because he has the most points and give it rank 1. And "Matt" at line 2 with rank 2?

Was it helpful?

Solution

Try this:

SELECT name,Wins,Points,Skills,@rn := @rn + 1 as Rank
FROM TableName, (SELECT @rn := 0 ) r
ORDER BY points DESC

Result (with the given data):

NAME    WINS    POINTS  SKILLS  RANK
Mark    4       2014    8       1
Matt    1       2009    2       2

See result in SQL Fiddle.

OTHER TIPS

You can do it in MySQL like this

select t.*, 
       @rank := @rank + 1 as rank
from your_table t
cross join (select @rank := 0) r
order by points desc

You don't mention DBMS, and the mysql trick presented above does not work, so I assume a DBMS with support for OLAP (psql, db2, oracle, mssql among other supports them)

select name,Wins,Points,Skills from ( SELECT name,Wins,Points,Skills , rank() over (order by points desc) as rnk FROM TableName ) order by rnk

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top