Jump to content

[SOLVED] Ordering a table from a ratio worked out by data in SQL


Recommended Posts

I have a SQL database that stores wins and losses, what I wish to do is order it in a table, so the people with the BEST ratio are at the top.

 

I don't know how to do this, at the moment it's just ordered by the most wins, then the ratio on the end of the table worked out using some basic PHP.

 

Here is my code:

 

<table width="40%">
  <tr>
  	<td class="th">#</td>
    <td class="th">Name:</td>
    <td class="th">Wins:</td>
<td class="th">Losses:</td>
<td class="th">W/L Ratio:</td>
  </tr>
<?php
	$count = 1;
		$sql  = "SELECT user_id, 2_wins, 2_losses FROM stats ORDER BY 2_wins DESC, 2_losses LIMIT 10";
		$result = mysql_query($sql);

		if(mysql_num_rows($result)!=0) { // (1)
		while(list($user_id, $wins, $losses) = mysql_fetch_row($result)) { // (2)
?>
  <tr>
  	<td><?=$count++?></td>
    <td>
<?php
	$result1 = mysql_query("SELECT username FROM users WHERE user_id = '$user_id'");
	while($row1 = mysql_fetch_array( $result1 ))
    	{
	echo $row1['username'];
	}
?>
</td>
    <td><?=$wins?></td>
<td><?=$losses?></td>
<td>
	<?php
	if($losses == '0' && $wins == '0') {
	echo "0%";
	} elseif($losses == '0' && $wins > '0') {
	echo "100%";
	} else {
	$ratio = ($wins / ($wins + $losses)) * 100;
	echo round($ratio) . '%';
	}
	?> 
</td>
  </tr>
<?php
}
}
echo "</table>";

?>

 

Greatly appreciated if anyone could help. :)

Your SQL will look something like this:

 

SELECT user_id, 2_wins, 2_losses, (2_wins/(2_wins + 2_losses)) AS ratio 
  FROM stats 
  GROUP BY user_id 
  ORDER BY ratio DESC LIMIT 10
-- I'm assuming there are no ties, er more precisely that the 2_wins + 2_losses == total_games_played

 

Best,

 

Patrick

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.