MySQL排名与分组

时间:2018-06-10 09:39:43

标签: mysql

我是新手,试图用不同的班级对学生进行排名,我的查询如下:

SELECT Branch, Grade, Section, RollNo, FIrst_Name, Father_Name, Grand_Father_Name, AverageMark, rank 
FROM (
    SELECT Branch, Grade, Section, RollNo, FIrst_Name, Father_Name, Grand_Father_Name, AverageMark, @curRank := IF(@prevRank = AverageMark, @curRank, @incRank) AS rank,  @incRank := @incRank + 1,  @prevRank := AverageMark 
    FROM studentsaverage p, 
        ( SELECT @curRank :=0, @prevRank := NULL, @incRank := 1 ) r 
    ORDER BY AverageMark DESC
) s

enter image description here

突出显示的学生排名是4而不是1,因为学生来自另一所学校,我该如何解决?

1 个答案:

答案 0 :(得分:0)

我实际上没有测试我的代码,但代码的问题在于你不能验证分支是否相同:

SELECT Branch,
       Grade,
       SECTION,
       RollNo,
       FIrst_Name,
       Father_Name,
       Grand_Father_Name,
       AverageMark,
       rank
FROM
    ( SELECT Branch,
             Grade,
             SECTION,
             RollNo,
             FIrst_Name,
             Father_Name,
             Grand_Father_Name,
             AverageMark,
             @curRank := IF(@curBranch = Branch ,IF(@prevRank = AverageMark, @curRank, @incRank),1) AS rank,
             @incRank := @incRank + 1,
             @prevRank := AverageMark,
             @curBranch = Branch
     FROM studentsaverage p,
         (SELECT @curRank :=0, @prevRank := NULL, @incRank := 1, @curBranch := NULL) r
     ORDER BY Branch, AverageMark DESC) s