【问题标题】:How to assign rank to students to where they share the highest rank when their scores equal?当他们的分数相等时,如何将排名分配给他们共享最高排名的学生?
【发布时间】:2017-12-01 22:38:49
【问题描述】:

我有对学生进行排名的代码,它可以工作,但不是我想要的——如果两个或多个学生得分相同 score 它不会 rank 他们都在同一个 rank。我希望最终的排名是这样的——如果两个或更多的学生score相同的结果,我希望他们rank在同一个地方像这样:

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

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

当前代码

$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>";
}

【问题讨论】:

标签: php mysql sorting sql-order-by


【解决方案1】:

你需要两个计数器

  • 绝对计数器(始终为 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 2022-01-26
    • 1970-01-01
    • 2021-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多