检索每个条目的最后一个条目

时间:2014-01-20 11:41:24

标签: sql sql-server

我有以下表格来评估学生:

StudentID | EvaluationStatusID| Date
1011010   |      1            |2013-11-07 20:31:51.000
1011020   |      1            |2013-11-08 13:23:51.000
1011010   |      2            |2013-11-08 20:31:51.000
1011020   |      3            |2013-11-09 20:31:51.000

学生的评估通过不同阶段进行 - “提交”,“评估”,“接受”等等。

我需要以“StudentID-EvaluationStatusID”形式获得每个学生的最新记录(按日期)。

所以,在上面的数据中,我应该返回以下内容:

1011010-2
1011020-3

在Sql server 2008中,我该怎么做?

3 个答案:

答案 0 :(得分:2)

最简单的是使用排名函数,如ROW_NUMBER

WITH CTE AS
(
    SELECT StudentID, EvaluationStatusID, Date,
           RN = ROW_NUMBER() OVER (PARTITION BY StudentID
                                   ORDER BY Date DESC)
    FROM dbo.Student
)
SELECT StudentID, EvaluationStatusID, Date
FROM CTE WHERE RN = 1

Demo

答案 1 :(得分:0)

    SELECT StudentID +' ' +EvaluationStatusID
    FROM tblTable T
    WHERE T.Date = (SELECT MAX(TT.Date) 
                    FROM tblTable TT
WHERE TT.StudentID  = T.StudentID  
)

答案 2 :(得分:0)

试试这个:

 With S1 as
    (
    select StudentID +''+EvaluationStatusID as Info, 
    ROW_NUMBER() OVER (PARTITION BY StudentID
                                       ORDER BY StudentID) as RC
     from students 
     )
     select * from S1 where S1.RC in (Select MAX(S1.RC)from S1)
     Group By Info, RC