我正在尝试返回名称&评分等级第三高的学生的成绩。我目前正在得到正确的答案,但我觉得有更好的方法来做到这一点。
数据集
CREATE TABLE Student(
Student_ID INT,
Student_Name VARCHAR(10)
)
INSERT INTO Student (Student_ID, Student_Name) VALUES (1,'Alex'),(2, 'Brett1'),(3,'Cora'),(4,'David'),(5,'Eleanor'),(6,'Brett2')
CREATE TABLE Grades(
Student_ID INT,
Assignment_ID INT,
Grade INT
)
INSERT INTO Grades (Student_ID, Assignment_ID, Grade) VALUES (1,10,90),(2,10,85),(3,10,75),(4,10,74),(1,11,80),(2,11,81),(4,11,88),(6,11,86),(2,12,84)
尝试解决方案
SELECT top 1 s.Student_Name, g.Grade
FROM Student s
INNER JOIN Grades g on s.Student_ID=g.Student_ID
WHERE g.Grade < 88
ORDER BY Grade DESC
没有(WHERE g.Grade&lt; 88)它返回前3个结果,这是解决问题的手动方法
提前致谢〜!
答案 0 :(得分:2)
只获得第3名,你可以使用前3名的TOP 1回复
select top 1 Student_name, Grade
from (
SELECT top 3 s.Student_Name, g.Grade
FROM Student s
INNER JOIN Grades g on s.Student_ID=g.Student_ID
ORDER BY Grade DESC ) t
order by Grade asc
答案 1 :(得分:2)
&#34;较新的&#34; SQL Server版本(SQL Server 2012 +):
SELECT s.Student_Name, g.Grade
FROM Student s
INNER JOIN Grades g on s.Student_ID=g.Student_ID
ORDER BY Grade DESC
OFFSET 2 FETCH FIRST 1 ROW ONLY
答案 2 :(得分:0)
使用ROW_NUMBER窗口功能
;with cte
AS (
SELECT s.Student_Name, g.Grade ,
RN = row_number()over(order by Grade desc)
FROM Student s
INNER JOIN Grades g on s.Student_ID=g.Student_ID
)
Select *
From cte
Where RN = 3