Sql 如何从表中选择上一条记录考虑年份和工作期间(月)

Sql 如何从表中选择上一条记录考虑年份和工作期间(月),sql,sql-server,Sql,Sql Server,我有一张这样的桌子: 我想要每个[Guid]的最后一个[Status],考虑最近的[Year]和[WorkingPeriodTitle]。 顺便说一下,我知道[WorkingPeriodTitle]应该替换为[WorkingPeriodId]。使用ROW\u NUMBER()窗口函数: select t.[PaymentAllocationGuid], t.[Status] from ( select *, row_number() over (partition by [

我有一张这样的桌子:

我想要每个[Guid]的最后一个[Status],考虑最近的[Year]和[WorkingPeriodTitle]。 顺便说一下,我知道[WorkingPeriodTitle]应该替换为[WorkingPeriodId]。

使用ROW\u NUMBER()窗口函数:

select
  t.[PaymentAllocationGuid], t.[Status] 
from (
  select *, 
    row_number() over (partition by [PaymentAllocationGuid] order by [Year] desc, [WorkingPeriodTitle] desc) rn
  from tablename
) t
where t.rn = 1

WorkingPeriodTitle
的相关性如何?每个GUID的最后状态不是每个GUID的
MAX(ID)
,因为ID是一个标识列吗?数据的微小图像对我们没有帮助。请花点时间以可消费的格式发布。
SELECT *,
    LAST_VALUE(Status) OVER (PARTITION BY PaymentAllocationGuid ORDER BY Year, 
    WorkingPeriodTitle RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)  
    AS LastStatus
FROM tablexyz