从属于另一个学生的先前排名中获取分数

fetch score from previous rank belonging to another student

我正在尝试为以下 select 语句中的每一行获取属于另一个学生的先前排名的分数。现在,我想在每个 CourseCode 和 StudentCode 的每个 GroupCode 中获得先前排名的分数。

SELECT StudentCode, CourseCode,GroupCode, Score, StudentRank
FROM Table

我的table数据

您可以使用 LAG 命令获取之前的值

SELECT LAG(StudentCode) prev_StudentCode,
       StudentCode,
       LAG(CourseCode) prev_CourseCode,
       CourseCode,
       LAG(GroupCode) prev_GroupCode,
       GroupCode,
       LAG(Score) prev_Score,
       Score,
       LAG(StudentRank) prev_StudentRank,
       StudentRank
FROM [Table];

您可以使用 apply :

SELECT StudentCode, CourseCode,GroupCode, Score, StudentRank, t1.What_u_want
FROM Table t OUTER APPLY 
     ( SELECT TOP 1 t1.Score AS What_u_want
       FROM Table t1
       WHERE t1.CourseCode = t.CourseCode AND 
             t1.GroupCode = t.GroupCode AND
             t1.StudentRank < t.StudentRank
             ORDER BY t1.StudentRank DESC
     );

然而,同样可以通过 相关性 方法实现:

SELECT StudentCode, CourseCode,GroupCode, Score, StudentRank, 
      (SELECT TOP 1 t1.Score AS What_u_want
       FROM Table t1
       WHERE t1.CourseCode = t.CourseCode AND 
             t1.GroupCode = t.GroupCode AND
             t1.StudentRank < t.StudentRank
             ORDER BY t1.StudentRank DESC
      ) What_u_want
FROM Table t1;