--- lib.php 2008-03-03 04:50:38.000000000 -0600
+++ lib.php 2008-11-18 13:41:46.000000000 -0600
@@ -263,6 +273,7 @@  
                     $data[] = '<span class="'.$hidden.$class.'">-</span>';;

                 } else {
+                    /* WRONG!
                     /// find the number of users with a higher grade
                     $sql = "SELECT COUNT(DISTINCT(userid))
                               FROM {$CFG->prefix}grade_grades
@@ -271,6 +282,25 @@ 
                     $rank = count_records_sql($sql) + 1;

                     $data[] = '<span class="'.$hidden.$class.'">'."$rank/$numusers".'</span>';
+                    */
+
+                    // Grab the context of the course in question
+                    $context = get_context_instance(CONTEXT_COURSE, $this->courseid);
+
+                    // This is the correct way find the number of users with a higher grade thet ARE STILL ENROLLED in the course.
+                    $sql = "SELECT COUNT(DISTINCT(g.userid))
+                              FROM {$CFG->prefix}grade_grades g
+                                INNER JOIN {$CFG->prefix}role_assignments r
+                                  ON r.userid = g.userid
+                             WHERE finalgrade IS NOT NULL AND finalgrade > $grade_grade->finalgrade
+                                AND itemid = {$grade_item->id}
+                                AND(r.contextid = $context->id)
+                                AND r.roleid IN ({$CFG->gradebookroles})";
+
+                    $rank = count_records_sql($sql) + 1;
+
+                    $data[] = '<span class="'.$hidden.$class.'">'."$rank/$numusers".'</span>';
+
                 }
             }

