MySQL如何对一个学生的分数/学科分数进行排名

时间:2018-08-29 20:03:35

标签: mysql sql database

所以我有一个叫做MARKS的表,我有这些列

STUDENT_ID, CLASSFORM_NAME, ACADEMIC_YEAR, TERM,  SUBJECT_NAME, TOTAL_MARKS

所以我想根据一位学生的科目名称,班级名称,学期和学年来选择总分的排名

这是我使用过但无法正常工作的查询

SELECT *
FROM (SELECT total_marks, @curRank := @curRank + 1 AS scorePosition
      FROM marks m, (SELECT @curRank := 0) q
      WHERE classform_name=? AND term=? AND academic_year=? AND subject_name=?
     ) t
WHERE student_id =?
ORDER BY total_marks DESC

帮帮我。谢谢。

1 个答案:

答案 0 :(得分:0)

您需要在分配排名之前 对数据进行排序。为了安全起见,请使用子查询:

SELECT m.*
FROM (SELECT m.*, @curRank := @curRank + 1 AS scorePosition
      FROM (SELECT m.*
            FROM marks m
            WHERE classform_name = ? AND term = ? AND academic_year = ? AND subject_name = ?
            ORDER BY total_marks DESC
           ) m CROSS JOIN
           (SELECT @curRank := 0) q
     ) m
WHERE m.student_id = ?;