Search code examples
phpmysqlpdoranking

Ranking a sum of values whose total is not stored in the database


I have a table with different exam records of four student all in the same class. The marks have not been summed up in the db. My question is ,is it possible to sum the marks of individual students on the front end and then place a rank on them? I have successfully summed marks on the front end but my rank code isn't working.The first table shows the database record while the second shows the result though the rank is empty :(

preview

result preview

here is my attempted rank code

    <?php

    $getrnk=$db->query("SELECT SUM(marks)FIND_IN_SET( marks, (    
    SELECT GROUP_CONCAT( marks
    ORDER BY marks DESC ) 
    FROM examresults )
      ) AS rank
    FROM examresults
    WHERE adm_no ='$reg'");

    $getrnk->execute();

    $rnk=$getrnk->fetch(PDO::FETCH_ASSOC);

    $strank=$rnk['rank'];
    echo $strank;

     ?>

Solution

  • Your code is quite clever, so let's work on making it work:

    SELECT SUM(marks),
           FIND_IN_SET(SUM(marks),
                       (SELECT GROUP_CONCAT(summarks ORDER BY summarks DESC ) 
                        FROM (SELECT SUM(marks) as summarks
                              FROM examresults
                              GROUP BY adm_no
                             ) sm
                       )
                      ) AS rank
    FROM examresults
    WHERE adm_no = '$reg';
    

    I'm impressed because I would never have thought of using find_in_set() to get the rank this way. Normally in MySQL, one would use variables for the ranking.