【问题标题】:SQL: Get last (highest) record on each row from the other table (GROUP BY?)SQL:从另一个表中获取每一行的最后(最高)记录(GROUP BY?)
【发布时间】:2023-03-15 12:40:01
【问题描述】:

以下是我的表格的以下记录: (我目前使用的是 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

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

【问题讨论】:

  • 什么 DBSM(例如 SQL-Server、MySql、Oracle)?

标签: sql-server select join group-by


【解决方案1】:
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

【讨论】:

  • 请注意(致@eibhrum)+ for Strings 是非标准语法,仅适用于 SQL Server。标准 SQL 使用 || 代替。
  • @LittleBobbyTables:我收到'MaxLevel'附近的语法错误。
  • @eibhrum - 抱歉,忘记了 MaxLevels 上的 join 子句,现在应该可以使用了
【解决方案2】:

试试这个:

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

【讨论】:

    【解决方案3】:

    您可以使用带有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
    

    【讨论】:

      【解决方案4】:
      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
      

      【讨论】:

        猜你喜欢
        • 2016-05-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-17
        • 1970-01-01
        相关资源
        最近更新 更多