我想根据学生的总成绩得到他们在班级中的排名/位置。
但是,我的查询一直向每个学生输出相同的排名;使它们都处于第一位置。
最初,我尝试了这个查询,它运行得很好,但它会显示出一个班级中的所有学生。
SELECT `student_id`, rank, totscore
FROM (SELECT *, IF(@marks=(@marks:=totscore), @auto, @auto:=@auto+1) AS rank
FROM (SELECT * FROM
(SELECT `student_id`, SUM(`ft_tot_score`) AS totscore, `class_id`, `section_id`
FROM ftscores_primary,
(SELECT @auto:=0, @marks:=0) as init WHERE class_id = 8 and section_id = 2 and session_id = 17
GROUP BY `student_id`) sub ORDER BY totscore DESC)t) as result
输出如下:
student_id | rank | totscore
402 | 1 | 869
1314 | 2 | 849
1024 | 3 | 842
但我想要这样的东西:
student_id | rank | totscore
1024 | 3 | 842
这就是我所做的
SELECT `student_id`, rank, totscore
FROM (SELECT *, IF(@marks=(@marks:=totscore), @auto, @auto:=@auto+1) AS rank
FROM (SELECT * FROM
(SELECT `student_id`, SUM(`ft_tot_score`) AS totscore, `class_id`, `section_id`
FROM ftscores_primary,
(SELECT @auto:=0, @marks:=0) as init WHERE class_id = 8 and section_id = 2 and session_id = 17 and student_id = 1024
GROUP BY `student_id`) sub ORDER BY totscore DESC)t) as result
这是我得到的
student_id | rank | totscore
1024 | 1 | 842
1条答案
按热度按时间kxeu7u2r1#
按如下方式修改查询:
请参见demo。