SQL:从另一个表(GROUP BY?)获取每一行的最后(最高)记录

时间:2012-07-25 14:30:42

标签: sql-server select join group-by

以下是我的表的以下记录: (我目前正在使用SQL Server 2008)

YearLevels

YearLevelID     YearLevelName
1               Freshman       
2               Sophomore       
3               Junior       
4               Senior   

学生

StudentID     FirstName     LastName
1             John          Doe
2             Peter         Pan
3             Mark          Twain

LevelsAttained

SSID     StudentID  YearLevelID
1        1          2
2        1          1
3        1          3
4        2          2
5        3          1
6        2          1

输出应为:

FullName     YearLevelName
John Doe     Junior
Peter Pan    Sophomore
Mark Twain   Freshman

4 个答案:

答案 0 :(得分:5)

SELECT FirstName + ' ' + LastName AS FullName, YearLevelName
FROM Students S
INNER JOIN (
    SELECT StudentID, MAX(YearLevelID) AS MaxLevel
    FROM LevelsAttained
    GROUP BY StudentID
) MaxLevels ON MaxLevels.StudentID = S.StudentID
INNER JOIN YearLevels Y ON Y.YearLevelID = MaxLevels.MaxLevel

答案 1 :(得分:1)

试试这个:

SELECT FirstName || ' ' || LastName AS FullName, l.YearLevelName AS YearLevelName
FROM  Students s
JOIN (SELECT StudentID, MAX(YearLevelID) AS LevelID FROM LevelsAttained GROUP BY StudentID) g0
ON g0.StudentID = s.StudentID 
JOIN YearLevels ON g0.LevelID = l.YearLevelID

答案 2 :(得分:1)

您可以使用带有ROW_NUMBER窗口函数的common-table-expression:

WITH CTE AS(
   SELECT RN = 
       ROW_NUMBER()OVER(PARTITION BY la.StudentID ORDER BY la.YearLevelID DESC)
   ,   FirstName + ' ' + LastName AS FullName
   ,   YearLevelName
   FROM Students s 
   INNER JOIN LevelsAttained la ON s.StudentID = la.StudentID 
   INNER JOIN YearLevels yl ON la.YearLevelID = yl.YearLevelID
)
SELECT FullName, YearLevelName FROM CTE WHERE RN = 1

答案 3 :(得分:1)

select s.firstname + ' ' + s.lastname, y.yearlevelname from
students s
inner join (select max(yearlevelid) yearlevelid, studentid from levelsattained group by studentid) l on s.studentid = l.studentid
inner join YearLevels y on l.yearlevelid = y.yearlevelid