使用sql对职位进行排名

f87krz0w  于 2021-06-15  发布在  Mysql
关注(0)|答案(3)|浏览(376)

试图排名的位置,但不是给予(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 = ?

.............................................................................

628mspwn

628mspwn1#

在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 = ?
                       );;
vdzxcuhz

vdzxcuhz2#

你不需要秩函数。您可以通过将表连接到自身来对行进行排序,在这种情况下,您可以选择如何确定顺序(和排名)。

ymdaylpp

ymdaylpp3#

我发现混合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 只包括一个随机的 total_marks 每个学号的值;使外和变得毫无意义。
编辑-这应允许位置进展根据关系“跳过”以后的位置: SELECT @curRank := @curRank + 1 AS counter, @prevRank := IF(@prev=@cur, @prevRank, @curRank) AS classPosition ... 省略 counter 从最后的结果来看,你必须扩展 * 明确地。

相关问题