获取上一行但使用日期而不是主日期

Get Previous Row but using Date, rather than Primary

我有以下示例数据,对于每个“人”标识符,我试图显示最新行 (EffectiveTo=NULL) 和之前行的字段值。

在没有要使用的数据的主键的情况下如何做到这一点?

预期输出为:

Create Table #temp
(
    Person int,
    Amount money,
    DailyAmount money,
    EffectiveFrom datetime,
    EffectiveTo datetime NULL
)

insert into #temp
(
    Person,
    Amount,
    DailyAmount,
    EffectiveFrom,
    EffectiveTo
)
select
    1,
    450,
    64.28,
    '2018-03-15 00:00:00.000',
    '2020-06-17 00:00:00.000'
union all
select
    1,
    500,
    71.42,
    '2020-05-22 00:00:00.000',
    '2020-06-18 00:00:00.000'
union all
select
    1,
    93.75,
    13.39,
    '2020-06-19 00:00:00.000',
    NULL    
union all
select
    2,
    200,
    28.57,
    '2019-02-05 00:00:00.000',
    '2020-01-02 00:00:00.000'
union all
select
    2,
    300,
    42.85,
    '2020-01-03 00:00:00.000',
    NULL    

select * from #temp

使用LEAD() OVER () window函数获取前几行数据

WITH mydata
AS (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY person ORDER BY EffectiveFrom DESC) rn,
              LEAD(amount) OVER (PARTITION BY person ORDER BY EffectiveFrom DESC) Prev_amount, 
              LEAD(DailyAmount) OVER (PARTITION BY person ORDER BY EffectiveFrom DESC) Prev_DailyAmount, 
              LEAD(EffectiveFrom) OVER (PARTITION BY person ORDER BY EffectiveFrom DESC) Prev_Eff_From, 
              LEAD(EffectiveTo) OVER (PARTITION BY person ORDER BY EffectiveFrom DESC) Prev_Eff_To
    FROM #temp
    )
SELECT Person, Amount, DailyAmount, EffectiveFrom, EffectiveTo, Prev_amount, Prev_DailyAmount, Prev_Eff_From, Prev_Eff_To
FROM mydata
WHERE rn = 1

Check Demo Here