我这里有一个非常简单的表。我要做的就是返回学生所在年级较高的那一行。我是SQL的初学者,不确定如何解决此问题。
表
Name Grade Class
Jim 7 Math
Jim 8 English
Emily 6 Science
Jason 11 Biology
Jason 11 Art
Jason 10 English
预期产量
Name Grade Class
Jim 8 English
Emily 6 Science
Jason 11 Biology
Jason 11 Art
答案 0 :(得分:1)
您可以使用以下类型查询:
SELECT T1.Name,Grade,Class FROM Table T1
INNER JOIN (SELECT Name,MAX(Grade) MaxGrade FROM Table GROUP BY Name) T2 ON T1.Name=T2.Name AND T1.Grade=T2.MaxGrade
答案 1 :(得分:1)
使用相关子查询的一种典型方法:
select t.*
from t
where t.grade = (select max(t2.grade) from t t2 where t2.name = t.name);
SQL Server还有另一个有趣的方法:
select top (1) t.*
from t
order by dense_rank() over (partition by name order by grade desc);
答案 2 :(得分:0)
SELECT t.Name
, t.Grade
, t.Class
FROM (
SELECT *
, Part = RANK() OVER(PARTITION BY Name ORDER BY Grade DESC)
FROM @t
) t
WHERE t.Part = 1