1

これが私のテーブルの次のレコードです:(私は現在SQLServer2008を使用しています)

年レベル

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 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ウィンドウ関数で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
于 2012-07-25T14:43:40.520 に答える
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 に答える