将历史记录插入新表中

时间:2017-04-13 15:08:38

标签: sql-server

我在这张桌子上工作,如下图所示它有名字,日期,ID和密钥。我想插入新表,其中old_name列维护该键的名称更改。输出结果也如下所示。感谢

STRING_AGG(channelgrouping, ' > ' ORDER BY date) AS channelgrouping_path

2 个答案:

答案 0 :(得分:1)

似乎非常适合 LAG()

Select id
      ,old_name = lag(name,1) over (Partition By [Key] Order by ID)
      ,name
      ,date
      ,[key]
 From YourTable
 Order By ID

答案 1 :(得分:0)

如果是SQL Server> = 2012

,则可以使用滞后
select *, lag(name,1,null) over(order by id) Old_name from #yourhistory

您的输入表

create table #yourhistory (id int, name varchar(20), date date, [key] int)

insert into #yourhistory 
  ( id  ,     name   ,     date             ,       [Key] ) values
     (    1    ,'charles  ','2004-05-07',              1001   )
    ,(    2    ,'CON      ','2004-05-07',              1001   )
    ,(    3    ,'Virginia ','2006-09-08',              1001   )
    ,(    4    ,'MART     ','2012-01-03',              1001   )
    ,(    5    ,'McDonalds','2013-12-30',              1001   )