1

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

年级

YearLevelID     YearLevelName
1               Freshman       
2               Sophomore       
3               Junior       
4               Senior   

学生

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

达到的水平

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

4 回答 4

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
于 2012-07-25T14:35:11.467 回答
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
于 2012-07-25T14:56:07.450 回答
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
于 2012-07-25T14:37:25.690 回答
1

您可以使用带有ROW_NUMBER窗口函数的公共表表达式:

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
于 2012-07-25T14:43:40.520 回答