使用同一列中的最新空值更新Null值

时间:2018-04-25 04:08:20

标签: sql sql-server

我有以下表结构:

CREATE TABLE #ORDERS (YEARMONTH NUMERIC, WAREHOUSE 
VARCHAR(50), CATEGORY_NUMBER INT, VALUE float)

INSERT INTO #ORDERS VALUES (201804, 'ABC', 1001,100)
INSERT INTO #ORDERS VALUES (201803, 'ABC', 1001,NULL)
INSERT INTO #ORDERS VALUES (201802, 'ABC', 1001,NULL)
INSERT INTO #ORDERS VALUES (201801, 'ABC', 1001,82)
INSERT INTO #ORDERS VALUES (201712, 'ABC', 1001,NULL)
INSERT INTO #ORDERS VALUES (201711, 'ABC', 1001,84)
INSERT INTO #ORDERS VALUES (201801, 'XYZ', 1022,NULL)
INSERT INTO #ORDERS VALUES (201802, 'XYZ', 1022,NULL)
INSERT INTO #ORDERS VALUES (201803, 'XYZ', 1022,77)

Input Table Data

我想要一个结果,这样每个月都应该有一个值。如果一个值对应于一个月的null,那么它应该为同一个仓库和category_number选择下一个notute值为yearmonth,因此,结果应如下所示:

Output Table Data

我成功地为单个仓库和类别编号实现了这个目标,但对于多个仓库和类别编号,我的逻辑失败了。 帮助将受到高度赞赏。

由于

2 个答案:

答案 0 :(得分:2)

您可以使用CTE和窗口函数:

with toupdate as (
      select t.*, 
             first_value(value) over (partition by warehouse
                                      order by (case when value is not null then 1 else 2 end), date desc
                                     ) as prev_value
      from t
     )
update toupdate
    set value = prev_value
    where value is null and prev_value is not null;

答案 1 :(得分:2)

将可更新 CTE subquery

一起使用
with cte as (
    select *, 
            coalesce(value, (select top 1 value from #orders 
                             where WAREHOUSE  = o.WAREHOUSE  and 
                             CATEGORY_NUMBER = o.CATEGORY_NUMBER and
                             yearmonth > o.yearmonth and 
                             value is not null
                             order by yearmonth) ) as Prev
    from #ORDERS o
)

update cte 
set value = Prev
where value is null;