我有一张表格如下
ID_STUDENT | ID_CLASS | GRADE
-----------------------------
1 | 1 | 90
1 | 2 | 80
2 | 1 | 99
3 | 1 | 80
4 | 1 | 70
5 | 2 | 78
6 | 2 | 90
6 | 3 | 50
7 | 3 | 90
我需要对它们进行分组,排序和排序并更新指定的排名:
ID_STUDENT | ID_CLASS | GRADE | RANK
------------------------------------
2 | 1 | 99 | 1
1 | 1 | 90 | 2
3 | 1 | 80 | 3
4 | 1 | 70 | 4
6 | 2 | 90 | 1
1 | 2 | 80 | 2
5 | 2 | 78 | 3
7 | 3 | 90 | 1
6 | 3 | 50 | 2
任何人都可以帮助我在mysql中实现这一目标。
答案 0 :(得分:0)
以下查询会按ID_CLASS
按GRADE
列的降序对结果组进行排序。
<强>查询强>
select `ID_STUDENT`, `ID_CLASS`, `GRADE`, (
case `ID_CLASS`
when @curA then @curRow := @curRow + 1
else @curRow := 1 and @curA := `ID_CLASS` end
) as `rank`
from `your_table_name` g,
(select @curRow := 0, @curA := '') r
order by `ID_CLASS`, `GRADE` desc;
答案 1 :(得分:0)
SELECT ID_STUDENT,ID_CLASS,GRADE,RANK
FROM
(
SELECT ID_STUDENT,ID_CLASS,GRADE,CASE WHEN @ID_CLASS=ID_CLASS THEN @RANK:= @RANK+1 ELSE @RANK :=1 END RANK,@ID_CLASS:=ID_CLASS
FROM STUDENT_TABLE,(SELECT @RANK :=0,@ID_CLASS:=1)Z ORDER BY ID_CLASS ASC,GRADE DESC
)ZZ;
您可以尝试以上查询。
答案 2 :(得分:0)
我们可以在这里使用会话变量来模拟排名。请注意,您确实在排名之后,而不仅仅是行号。这样做的原因是,给定班级中的两个或更多学生可以与同一年级相关联。您的示例数据不包含此类边缘情况,但案例存在于您的问题中。我选择在这里使用密集等级,这意味着如果一个班级给了学生以下等级:
student | grade | dense rank
1 | 90 | 1
2 | 90 | 1
3 | 90 | 1
4 | 80 | 2
5 | 65 | 3
然后,最高等级的三方并列将意味着所有三个学生将成为第一,而下一个最高的学生将成为第二个。另一种方法是使用排名,在这种情况下,下一个最高的学生将排名第4。
SET @dr = 1;
SET @id_class = NULL;
SET @grade = NULL;
SELECT
ID_STUDENT,
@dr:=CASE WHEN (@id_class = ID_CLASS AND @grade <> GRADE) THEN @dr + 1
WHEN (@id_class = ID_CLASS AND @grade = GRADE) THEN @dr
ELSE 1 END AS dr,
@id_class:=ID_CLASS AS ID_CLASS,
@grade:=GRADE AS GRADE
FROM yourTable
ORDER BY
ID_CLASS,
GRADE DESC;
<强>输出:强>
在这里演示:
答案 3 :(得分:-1)
UPDATE youre_tbl t2
SET t2 .RANK= (SELECT *
FROM youre_tbl t
ORDER BY t.GRADE)
FROM t2
WHERE t2.ID = t.ID
您可以从中获得有序的结果。
答案 4 :(得分:-1)