SQL:如何使用下一个可用值填充空单元格?

时间:2017-10-05 02:08:14

标签: sql sql-server null

我希望从下一个可用值中获取空列的值。

enter image description here

我尝试了这段代码,但我得到了之前的值

DROP TABLE #X
CREATE TABLE #X
(
    ID INT IDENTITY PRIMARY KEY
    ,v INT
);

INSERT INTO #X
SELECT 121 UNION ALL SELECT NULL UNION ALL SELECT NULL 
UNION ALL SELECT 312 UNION ALL SELECT NULL UNION ALL SELECT NULL UNION ALL SELECT NULL
UNION ALL SELECT 123 UNION ALL SELECT NULL UNION ALL SELECT NULL 
UNION ALL SELECT 415 UNION ALL SELECT NULL UNION ALL SELECT NULL UNION ALL SELECT NULL UNION ALL SELECT NULL
UNION ALL SELECT 200;

SELECT * FROM #X;

DECLARE @v INT;

UPDATE #x WITH(TABLOCKX)
SET @v = v = CASE WHEN v IS NULL THEN @v ELSE v END
OPTION(MAXDOP 0);

SELECT * FROM #x;

1 个答案:

答案 0 :(得分:0)

您的数据每个商品代码只有一个值。如果您的数据一般如此,您可以这样做:

select t.*, max(amount) over (partition by item_code)
from t;

如果您想更新金额,请:

with toupdate as (
      select t.*, max(amount) over (partition by item_code) as new_amount
      from t
     )
update toupdate
    set amount = new_amount
    where amount is null;