我有一个Student
表,其中包含以下列:
studentName
,startYear
,EndYear
,classId
,更多列
此表包含不同班级学生的startYear和EndYear。
我想编写一个查询来查找最长年份(diff b / w EndYear和startYear)传递课程的所有学生姓名。
我想在选择查询中跟踪三个字段
select studentName, classId, max(EndYear- startYear) as maxYears from Students group by classId;
但由于group by不包含studentname,因此此查询失败(并且它也有意义)。
然后我可以这样做: 将以下查询的结果放在临时表TEMP中:
select classId, max(EndYear- startYear) from Students group by classId
然后将此临时表与学生表联系起来。
select studentName, classId, EndYear- startYear from Student s join Temp t on s.classId = t.classId and (s.EndYear- s.startYear) = t.maxYears
但这对我来说并不是最佳选择。我想知道还有什么方法可以做到这一点。
答案 0 :(得分:0)
以下带有correlated sub-query
的脚本应该等同于JOIN
解决方案,甚至可以由SQL Server优化器转换为JOIN
。
SELECT studentName, classId
FROM Students s
WHERE (EndYear- startYear) = (SELECT MAX(EndYear- startYear)
FROM Students sm
WHERE c.classId = sm.classId)
答案 1 :(得分:0)
尝试此查询,该查询执行自联接以获取具有最大值的行(EndYear- startYear):
select s1.studentName, s1.classId, s1.EndYear-s1.startYear
from Student s1
inner join
(
select classId, max(EndYear- startYear)
from Students
group by classId
) s2
on s1.classId = s2.classId;
答案 2 :(得分:0)
试试这个:
SELECT *
FROM (
SELECT studentName, startYear, EndYear, classId,
DENSE_RANK() OVER(PARTITION BY classId ORDER BY endYear - startYear DESC) AS Rnk
FROM dbo.Student
) x
WHERE x.Rnk = 1;