根据 Rank1 值列数据更新 Rank 2 值

Update the Rank 2 values based on Rank1 value column data

table中的数据如下:

查询: select ID,actv_ind,valid_from,valid_to,rnk 来自#ABC

预期数据如下: 我想将 Rank 2 记录的 Valid_from 日期设置为 (Valid_from Rnk 1 记录的日期 - 1)

已尝试查询:

select t1.id, t1.actv_ind, t1.rnk, case when t1.rnk >1 then t1.valid_from end VF1, case when t2.rnk > 1 then t1.valid_from - 1 end VF2
from #ABC t1
inner join #ABC t2
on t1.id = t2.id
and t1.actv_ind = t2.actv_ind

只需使用LAG:

SELECT mtrl_id,
       actv_ind,
       rnk
       LAG(DATEADD(DAY, -1, valid_from),1,valid_from) OVER (PARTITION BY mtrl_id ORDER BY Rank) AS valid_from,
       valid_to
FROM dbo.YourTable;