输出:https://www.dropbox.com/s/q9bjrzndbzj0l2i/test3.PNG?dl=0
如果我想只获取Position(row_number)= 3,如果让我们说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;
谢谢!
答案 0 :(得分:1)
对查询使用子选择,并使用所需的行号
对其进行过滤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