【问题标题】:Create ID column based on last update date column根据上次更新日期列创建 ID 列
【发布时间】:2021-01-13 13:00:09
【问题描述】:

我将创建表,其中IDPRIMARY KEY。我将插入列:NameABSValueLastUpdateDate = GETDATE()

问题是我想生成PctChange 值,例如等于:(val1_5 - val1_1) / val1_prev * 100(下划线后面的数字是 ID 值)。

我的问题是如何得到以前的值,所以我可以计算出PctChg?插入时可以这样做吗?

ID Name ABSValue PctChg LastUpdateDate
1 val 1 13 0% 2021/01/08
2 val 2 45 0% 2021/01/08
3 val 3 3 0% 2021/01/09
4 val 2 50 11% 2021/01/09
5 val 1 10 -23% 2021/01/13

【问题讨论】:

  • 我不按照计算。 val1_5 是什么?
  • val 1 在第 5 行,或者如果您查看 LastUpdateDate,则为最后添加的值

标签: sql sql-server sql-insert


【解决方案1】:

此方法假定表上存在唯一键 (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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-03
    • 2021-05-20
    • 1970-01-01
    • 1970-01-01
    • 2021-02-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多