Read the row_number

夙愿已清 提交于 2019-12-11 23:38:17

问题


Output: https://www.dropbox.com/s/q9bjrzndbzj0l2i/test3.PNG?dl=0

How do I incorporate a query into the current code if I want to get only the Position (row_number) = 3 if lets say the Stud_ID = 4?

SET @row_num = 0; 
SELECT @row_num := @row_num + 1 as Position, s.* 
FROM
(
    SELECT
        Student.Stud_ID, Student.Stud_Name, Student.Stud_Class, SUM(Grade.Percentage) AS Points 
    FROM Student, Student_Subject, Grade 
    WHERE Student.Stud_ID = Student_Subject.Stud_ID 
        AND Student_Subject.Stud_Subj_ID = Grade.Stud_Subj_ID 
        AND Student.Stud_Form = '1' 
        AND Grade.Quarter = '1' 
    GROUP BY Student.Stud_ID 
    ORDER BY Points DESC
) AS s;

Thanks!!


回答1:


Use a subselect over your query and filter it with your desired row number

SELECT * 
FROM (
SELECT @row_num := @row_num + 1 AS `Position`, s.* 
FROM
(
    SELECT
        Student.Stud_ID, Student.Stud_Name, Student.Stud_Class, SUM(Grade.Percentage) AS Points 
    FROM Student, Student_Subject, Grade 
    WHERE Student.Stud_ID = Student_Subject.Stud_ID 
        AND Student_Subject.Stud_Subj_ID = Grade.Stud_Subj_ID 
        AND Student.Stud_Form = '1' 
        AND Grade.Quarter = '1' 
    GROUP BY Student.Stud_ID 
    ORDER BY Points DESC
) AS s
CROSS JOIN (SELECT @row_num := 0) AS s1
) AS t 
WHERE t.Position = 3


来源:https://stackoverflow.com/questions/27837752/read-the-row-number

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!