如何在mysql中增加一个值?我想找到max tot必须为1的学生成绩,依此类推

问题描述 投票:0回答:1

enter image description here

我希望在每行之后递增一个值@a值必须递增

SET @a=1;
SELECT  @a,std_id,SUM(`read_mark`+`write_mark`+`homework`+`classwork`) AS tot FROM tbl_exam
where `class_detail_id`=26 AND YEAR(`date`)=1397 GROUP BY `std_id` ORDER BY
SUM(`read_mark`+`write_mark`+`homework`+`classwork`) DESC;
SET @a=@a+1;
mysql mysqli
1个回答
0
投票

你可以尝试下面

SET @a = 0;

select (@a:=@a + 1) AS num,* from
(SELECT 
    std_id,SUM(`read_mark`+`write_mark`+`homework`+`classwork`) AS tot 
    FROM tbl_exam
    where `class_detail_id`=26 AND YEAR(`date`)=1397 GROUP BY `std_id` 
   ORDER BY tot  DESC
)X

对于MYSql Version 8+,您可以使用窗口函数row_number()

select row_number() over(partition by std_id order by tot desc) as num,*
from
(SELECT 
        std_id,SUM(`read_mark`+`write_mark`+`homework`+`classwork`) AS tot 
        FROM tbl_exam
        where `class_detail_id`=26 AND YEAR(`date`)=1397 GROUP BY `std_id` 
       ORDER BY tot  DESC
 )X
© www.soinside.com 2019 - 2024. All rights reserved.