Jump to content

Get a ranking based on the sum of a user's score?


freaksauce

Recommended Posts

Each score submitted inserts a new row, I have the following query to order the users scores by the sum of their scores.

 

SELECT *, SUM(score) as sum
FROM `scores`
GROUP BY user_id
ORDER BY sum DESC

 

Now I need some way of getting their rank by counting the number of rows greater than the score. So something like:

 

SELECT *, SUM(score) as sum, COUNT(sum) as rank
FROM `scores`
GROUP BY user_id
WHERE sum > 100
ORDER BY sum DESC

 

Does that make any sense?

 

Server version: 5.0.24a-community

PHP Version 5.1.6

Link to comment
Share on other sites

<?php 
mysql_query ("CREATE TEMPORARY TABLE tmpx SELECT user_id, SUM(score) as score FROM ratings GROUP BY user_id");
mysql_query ("CREATE TEMPORARY TABLE tmpy SELECT user_id, SUM(score) as score FROM ratings GROUP BY user_id");

$sql = "SELECT x.user_id, x.score,
        (SELECT COUNT(*)+1 FROM tmpy WHERE score > x.score) as position
         FROM tmpx x
         ORDER BY position";
$res = mysql_query($sql) or die (mysql_error()."<p>$sql</p>");
while (list ($pid, $sc, $pos) = mysql_fetch_row($res))
{
    echo "$pid ($sc) : $pos <br/>";
}
?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.