如何从每个学生的第二条最新记录中获取数据?

How to grab data from the 2nd most recent record for each student?

我在学区工作,我有一个数据库,其中包含有关学生教育计划的信息。我正在使用 Management Studio 访问 SQL Server 2012 数据库。我需要从他们的第二个最新计划中获取信息。这是列。

列:

我知道如何创建一个查询来获取最近的一个,但不是第二个最近的。我需要每个学生的第二个最新记录。任何帮助将不胜感激!

如果要获取 n'th 记录,请使用 row_number

select * from 
(select studentid , 
 plandata ,
 row_number() over(partition by plandata order by plandata desc) rn
from dbo.plans) t
where t.rn=2 -- or n

使用ROW_NUMBER函数,按StudentID划分:

WITH A AS
(
  SELECT 
    StudentID , 
    PlanDate ,
    MeetingDate,
    ROW_NUMBER() OVER(PARTITION BY StudentID ORDER BY PlanDate DESC) rownum
  FROM dbo.plans
) 
SELECT * FROM a
WHERE rownum=2 

请试试这个:

select * from
    (select *, row_number() over (partition by StudentID order by PlanDate desc) Rank
     from dbo.plans) p
where p.Rank = 2

参考link:https://msdn.microsoft.com/en-us/library/ms186734.aspx

试试这个;

select * from
(
  select *, ROW_NUMBER() 
  over(partition by StudentID order by plandate desc) 
  as Row from dbo.plans
) temp
WHERE temp.Row = 2