所以,我的问题是在这个上下文中插入的: 我有一个管理学生课外课程申请的系统。这些应用程序存储在具有以下结构的表中:
我的问题是:对于每个学生和课程,我需要获得最新的一行。
StudentId CourseId StatusVarificationDate Status
1 1001 2011-12-12 07:27:24 In Progress
1 1001 2011-12-12 09:27:24 In Progress
1 1002 2011-12-13 15:27:24 Admited
2 1001 2011-12-12 09:27:24 In Progress
2 1001 2011-12-12 15:27:24 Admited
通过上面的例子,我怎样才能得到这个结果?
StudentId CourseId StatusVerificationDate Status
1 1001 2011-12-12 09:27:24 In Progress
1 1002 2011-12-13 15:27:24 Admited
2 1001 2011-12-12 15:27:24 Admited
答案 0 :(得分:1)
通常使用row_number()
处理:
select t.*
from (select t.*,
row_number() over (partition by StudentId, CourseId
order by StatusVarificationDate desc
) as seqnum
from t
) t
where seqnum = 1;
答案 1 :(得分:0)
在JOIN语句中使用MAX聚合函数:
SELECT *
FROM table1
JOIN
(
SELECT StudentId, CourseId MAX(StatusUpdateDate) Maxdate
FROM table1
) A ON A.Maxdate = StatusUpdateDate AND A.StudentId = table1.StudentId
答案 2 :(得分:0)
将 ROW_NUMBER()与分区一起使用,如下所示:
;With T AS
(
SELECT
*,
ROW_NUMBER() OVER(PARTITION BY StudentId,CourseId ORDER BY StatusVarificationDate DESC) AS PartNo
FROM @tblTest
)
SELECT
*
FROM T
WHERE PartNo=1