Reputation: 49
I have table in my data base which is storing the score of users table looks like this.
id user_id user_score
2748 371 3
2253 353 2
2254 353 2
2255 353 2
2256 353 2
2257 353 2
2258 353 2
2259 353 2
I want to calculate each users total score from this table and need to out put user name like this
user_id user_Score
357 x
367 y
354 z
Here x>y>z Php code i am writing is something looks like this
<?php
//Expected query is contains user_id and user_query
$query="Expected query";
$connection=mysqli_connect("Connection varables");
$data=mysqli_query($connection,$query);
while($row=mysqli_fetch_array($data)){
echo "User name:";
echo $row['user_id'];
echo "</br>";
echo "Score:";
echo $row['user_score'];
echo "</br>";
}
?>
How to do this?.
Upvotes: 0
Views: 1047
Reputation: 42460
SELECT user_id, MAX(user_score) as max_score
FROM your_table
GROUP BY user_id
ORDER BY max_score DESC
should be what you are looking for if I understood you correctly.
It gives you for each user the user's user_id
as well as the user's highest score, sorted by the highscores.
Edit: If you are looking for the sum of all scores per user, this query will do the trick instead:
SELECT user_id, SUM(user_score) as score_sum
FROM your_table
GROUP BY user_id
ORDER BY score_sum DESC
Upvotes: 2