Question

my question is finding out how to label the top 3 entries based on column "avg_score, in a table, while still showing the rest of the entries, but without a label. So say I have a table like this:

 Entry   avg_score

entry_1 | 4.3
entry_2 | 9.4
entry_3 | 4.6
entry_4 | 7.1
entry_5 | 2.1
entry_6 | 1.9

I want to be able to find the top 3 based on the column 'avg_score' and display it like:

"1st place: entry_2

2nd place: entry_4

3rd place: entry_3

entry_1

entry_5

entry_6"

Any help would be appreciated!

Was it helpful?

Solution 2

At first you must make your query which would order by avg_score desceing.

After that you can do something like this:

<?
$x = 1;
while($row = mysql_fetch_array($q)){
    if($x < 4){
        echo $x.". place: ";
    }
    echo $row['Entry'];
}
?>

if you want it to show 1st etc then use:

<?
$x = 1;
while($row = mysql_fetch_array($q)){
    if($x == 1){echo "1st place: ";
    }elseif($x == 2){echo "2nd place: ";
    }elseif($x == 3){echo "3rd place: ";}
    echo $row['Entry']."<br />";
    $x++;
}
?>

OTHER TIPS

The canonical way to do this is to define a rank and then use the rank to determine the strings to prepend to the entry name:

select concat(case when rank = 1 then '1st place: '
                   when rank = 2 then '2nd place: '
                   when rank = 3 then '3rd place: '
                   else ''
              end, entry)
from (select t.*, @rank := @rank + 1 as rank
      from t cross join (select @rank := 0) const
      order by avg_score desc
     ) t
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top