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

时间:2018-06-29 08:56:16

标签: sql sql-server rank sql-server-2005-express

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

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

我的表格数据

enter image description here

2 个答案:

答案 0 :(得分:1)

您可以使用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
     );

但是,使用 correlation 方法也可以实现同样的效果:

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;

答案 1 :(得分:0)

您可以使用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];