SQL 查询以获取最近的行

SQL query to get most recent row

我有一个学生历史记录 table,它维护每个学生的注册部分历史记录。例如,学生 X 目前在第 1 部分,而学生 X 过去可能在其他部分(包括过去在第 1 部分的注册)。

每次学生 X 更改到另一个部分时,都会将一条记录添加到学生历史记录中 table。

学生历史 table 具有以下结构: Student IdDate_enteredsection_id

我需要编写一个 SQL 查询来获取以下场景的记录:

获取第 1 和第 2 部分当前所有学生的 Student Id(最近 date_entered 的学生必须是第 1 部分或第 2 部分)。结果不应包括过去在这些部分 1 和 2 中的任何学生。

示例查询:

select student_id from student_Queue_history where section_id in (1, 2) 

有人可以帮我写查询吗?

您的 table 存在一些非常具有挑战性的设计缺陷,但您可以利用 ROW_NUMBER 来解决这个问题。从性能的角度来看,这不是最好的,但次优的设计限制了您的能力。请注意,这仍然主要是猜测,因为您没有在此处提供太多详细信息。

with CurrentStudents as
(
    select *
        , ROW_NUMBER() over(partition by student_id order by date_entered desc) as RowNum
    from student_Queue_history
)
select *
from CurrentStudents
where section_id in (1, 2)
    and RowNum = 1

您可以先 select 每个学生的最大日期,然后 join 返回 student_history table。

with maxdate as (
select student_id, max(date_entered) as mxdate 
from student_history
group by student_id)
select s.* 
from student_history s 
join maxdate m on s.student_id = m.student_id and s.date_entered = m.mxdate
where s.section_id in (1,2)
select a.student_id 
from student_Queue_history as a
where a.section_id in (1, 2) 
  and not exists (select b.student_id from student_Queue_history as b where b.student_id = a.student_id and b.Date_entered > a.Date_entered)