尝试对排名进行排名,但是在第3个位置出现平局时,不给出(1,2,3,3,5 ..),而是给出(1,2,3,4,5 ...)。 。 请帮助 下面是代码..谢谢 ................................................... ...........................
SELECT t.*
FROM (SELECT @curRank := IF(@prev= @cur, @curRank, @curRank + 1 ) AS classPosition,student_id, @prev:=@cur, @cur:=SUM(total_marks)
FROM (SELECT m.*
FROM marks m
WHERE classform_name = ? AND term = ? AND academic_year = ? GROUP BY student_id
ORDER BY SUM(total_marks) DESC
) n CROSS JOIN
(SELECT @curRank := 0, @prev:=NULL, @cur:=NULL ) q GROUP BY student_id
) t
WHERE student_id = ?
............................................... .....................
答案 0 :(得分:0)
排名是MySQL的真正痛苦。
如果您希望在这些条件下获得单个学生的排名,我建议:
SELECT 1 + COUNT(*)
FROM marks m
WHERE m.classform_name = ? AND m.term = ? AND m.academic_year = ? AND
m.total_marks >= (SELECT m2.total_marks
FROM marks m2
WHERE m2.classform_name = m.classform_name AND
m2.term = m.term
m2.academic_year = m.academic_year
m2.student_id = ?
);;
答案 1 :(得分:0)
您不需要RANK函数。您始终可以按joining the table to itself对行进行排名,在这种情况下,您可以选择确定顺序(和排名)的方式。
答案 2 :(得分:0)
我混用了session / @变量,并且聚合可能有点不可靠,但是您可以尝试将select表达式的顺序更改为
student_id, @cur:=SUM(total_marks), @curRank := IF(@prev= @cur, @curRank, @curRank + 1 ) AS classPosition, @prev:=@cur
如果这没有帮助,建议您将汇总和排名分开。实际上,您已经在子查询中求和了,所以我不确定为什么您不只是将和包括在n
的结果中。
SELECT * FROM (
SELECT @curRank := IF(@prev= @cur, @curRank, @curRank + 1 ) AS classPosition, student_id, @prev:=@cur, @cur:=overall
FROM (SELECT m.*, SUM(total_marks) AS overall
FROM marks m
WHERE classform_name = ? AND term = ? AND academic_year = ?
GROUP BY student_id
ORDER BY overall DESC
) AS n
CROSS JOIN (SELECT @curRank := 0, @prev:=NULL, @cur:=NULL ) AS q
) AS completeRankings
WHERE student_id = ?
实际上,您的原始查询应该还是有其他问题。 n
仅应为每个student_id包含一个随机的total_marks
值;使外部SUM毫无意义。
编辑-根据联系,位置应该可以前进到“跳过”以后的位置:
SELECT @curRank := @curRank + 1 AS counter, @prevRank := IF(@prev=@cur, @prevRank, @curRank) AS classPosition
...要从最终结果中省略counter
,则必须显式扩展*
。