Nicholas Teh Sek Kit
Nicholas Teh Sek Kit

Reputation: 11

Read the row_number

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!!

Upvotes: 0

Views: 57

Answers (1)

M Khalid Junaid
M Khalid Junaid

Reputation: 64466

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

Upvotes: 1

Related Questions