当学生的分数相等时,如何为学生分配排名最高的等级?

时间:2017-06-28 13:57:34

标签: php mysql sorting sql-order-by

我有一些代码可以对学生进行排名并且有效,但不是我想要的 - 如果两个或多个学生得分相同score它们不会rank他们在同一个rank {1}}。我希望最终排名是这样的 - 如果两个或更多学生score得到相同的结果,我希望他们rank在同一个地方这样:

1. miki ==> 97.8
2. lisa ==> 96.1 
2. jack ==> 96.1
4. john ==> 90.7 

请注意,lisa和jack score相同(96.1),并且它们给它们相同的rank(第二个),因此跳过第3个。约翰是第四名。

当前代码

$student = '10_E';
$first = mysql_query("SELECT * FROM rej_students where student_selected = '$student'");

$teacher = mysql_query("SELECT * FROM teachers WHERE tech_id = '1002'");
$teachers = mysql_fetch_array($teacher);

$avg = mysql_query("SELECT * FROM avgfct_10 order by AVGFCT_10 desc");

$ra = 0; //rank
while ($go = mysql_fetch_array($avg))
{
    if ($go['AVGFCT_10'] != $go['AVGFCT_10'])
    {
        $micky = $ra ++;
    }
    if ($go['AVGFCT_10'] == $go['AVGFCT_10'])
    {
        $micky = 'same';
    }
    echo "id = " . $go['STUDENT_ID'] . "<br> AVARANGE = " . $go['AVGFCT_10'] . "<br>RANK = " . $micky . "<br> Class = " . $teachers['tech_hclass'] . "<br><br>";
}

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:0)

你需要两个计数器

  • 绝对计数器(始终为1,2,3,4,5等)。
  • 排名计数器 - 它从1开始计算,但如果分数相同,则不会更新。只要分数不同,它就会随absolute counter更新。

示例代码

$counter = 1; // init absolute counter
$rank = 1; // init rank counter

// initial "previous" score:
$prevScore = 0;
while ($go = mysql_fetch_array($avg))
{
    // get "current" score
    $score = $go['AVGFCT_10'];

    if ($prevScore != $score) // if previous & current scores differ
        $rank = $counter;
    // else //same // do nothing

    echo "Rank: {$rank}, Score: {$score}<br>";
    $counter ++; // always increment absolute counter

    //current score becomes previous score for next loop iteration
    $prevScore = $score;
}

输出:

Rank: 1, Score: 97.8
Rank: 2, Score: 96.1
Rank: 2, Score: 96.1
Rank: 4, Score: 90.7