插入上一行

时间:2018-09-10 16:02:57

标签: sql sql-server tsql

我有下表:

DECLARE @TempTable TABLE
(
    ID int,
    Lastname nvarchar(50),
    Firstname nvarchar(50),
    Age int
)

insert into @TempTable (ID, Lastname, Firstname, Age)
VALUES(1, 'Smith', NULL, NULL),
    (2, NULL, 'Will', 40),
    (3, NULL, 'Jaden', 20),
    (4, 'Matt', NULL, NULL),
    (5, NULL, 'Damon', 39)

enter image description here

我要使用“ 更新”更改表,如下所示:

enter image description here

我知道函数“滞后”和“前导”。但是据我了解,它们不能用于 UPDATE 表达式

2 个答案:

答案 0 :(得分:2)

Microsoft SQL解决方案

select id ,

(

    select Lastname from @TempTable c  where c.ID < p.id AND c.Lastname is not null group by Lastname
 order by max(id) desc OFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY  

) as Lastname, 

FirstName,
Age

from @TempTable p
where Firstname is not null;

提琴:http://sqlfiddle.com/#!18/4922f/15

示例:http://rextester.com/IKG65840

答案 1 :(得分:1)

以下是使用df[~df.index.duplicated(keep='first')] 的一种选择:

correlated subquery