用先前的NOT NULL行更新NULL行

时间:2019-06-13 13:43:56

标签: sql sql-server tsql sql-server-2008 sql-server-2008-r2

我有一个方案,其中我的表有2列,一列有一系列日期,另一列有一些值。现在,我需要使用与最新日期相对应的值来更新空值,如下所示。

enter image description here

我不能像使用SQL Server 2008R2一样使用LEAD和LAG函数。

样品数据在下面。

DECLARE @Table TABLE
(
    Date_D DATE,
    Val INT
);

INSERT INTO @Table
(
    Date_D,
    Val
)
VALUES
('2019-06-15', 2),
('2019-06-16', NULL),
('2019-06-17', NULL),
('2019-06-18', 7),
('2019-06-19', 1),
('2019-06-20', 5),
('2019-06-21', NULL),
('2019-06-22', NULL),
('2019-06-23', NULL),
('2019-06-24', NULL),
('2019-06-25', 9),
('2019-06-26', 5),
('2019-06-27', 3),
('2019-06-28', 4),
('2019-06-29', NULL),
('2019-06-30', 1)



SELECT * FROM @Table

3 个答案:

答案 0 :(得分:3)

使用相关子查询进行更新:

UPDATE T0
SET Val = (
    SELECT TOP 1 Val
    FROM @Table As T1
    WHERE Val IS NOT NULL
    AND T0.Date_D > T1.Date_D
    ORDER BY Date_D DESC
    ) 
FROM @Table As T0
WHERE Val IS NULL

验证:

SELECT *
FROM @Table

结果:

Date_D          Val
15.06.2019      2
16.06.2019      2
17.06.2019      2
18.06.2019      7
19.06.2019      1
20.06.2019      5
21.06.2019      5
22.06.2019      5
23.06.2019      5
24.06.2019      5
25.06.2019      9
26.06.2019      5
27.06.2019      3
28.06.2019      4
29.06.2019      4
30.06.2019      1

答案 1 :(得分:0)

执行此操作的一种方法是使用子选择,在当前Date_D之前选择TOP 1非NULL值。

答案 2 :(得分:-1)

您可以照做

SELECT Date_D, CASE WHEN Val IS NULL THEN
          (
            SELECT TOP 1 Val 
            FROM @Table 
            WHERE Val IS NOT NULL AND Date_D < T.Date_D 
            ORDER BY Date_D DESC
          ) ELSE Val END
FROM @Table T;

如果要更新表,则将其与结果结合起来。

对于UPDATE

;WITH CTE AS
(
  SELECT Date_D, CASE WHEN Val IS NULL THEN
            (
              SELECT TOP 1 Val 
              FROM @Table 
              WHERE Val IS NOT NULL AND Date_D < T.Date_D 
              ORDER BY Date_D DESC
            ) ELSE Val END Val
  FROM @Table T
)
UPDATE T
SET T.Val = CTE.Val
FROM @Table T INNER JOIN CTE
ON T.Date_D = CTE.Date_D
WHERE T.Val IS NULL; --You can also AND Date_D BETWEEN StartDate AND EndDate

查看它在live demo上的工作方式