此方法假定表上存在唯一键 (Name, LastUpdateDate) 约束。要插入的值被声明为变量。然后在 CTE 中选择声明的变量,并使用 OUTER APPLY 来定位每个名称的原始(根据 LastUpdateDate)行。百分比变化计算为 DECIMAL(14, 2)。像这样的。
/* values to insert */
declare
@Name varchar(20)='val1',
@ABSValue int=10,
@LastUpdateDate date=getdate();
/* use the select statement to insert into table */
;with
all_cte([Name], ABSValue, LastUpdateDate) as (
select 'val1', 14, cast(dateadd(day, -5, getdate()) as date)
union all
select 'val1', 10, cast(dateadd(day, -3, getdate()) as date)
union all
select 'val3', 10, cast(dateadd(day, -1, getdate()) as date)
union all
select 'val1', 10, cast(dateadd(day, -1, getdate()) as date)),
ins_cte([Name], ABSValue, LastUpdateDate) as (
select @Name, @ABSValue, @LastUpdateDate)
select i.*, oa.*,
cast(case when oa.ABSValue is null then 0
else (i.ABSValue-oa.ABSValue)/(oa.ABSValue*1.0)*100 end as decimal(14, 2)) calc_pct_change
from ins_cte i
outer apply (select top(1) ABSValue
from all_cte a
where i.[Name]=a.[Name]
and i.LastUpdateDate>a.LastUpdateDate
order by LastUpdateDate) oa;
输出
Name ABSValue LastUpdateDate ABSValue calc_pct_change
val1 10 2021-01-13 14 -28.57