SQL Server:用上一个单元格中的值填充空行

时间:2018-10-21 11:24:58

标签: sql sql-server

我有一个关于空行的问题;我的SQL Server表如下所示:

enter image description here

每个项目的ItemNo列是固定的。如何将LabelSeriesAmount的值插入ItemNo

我尝试过:

UPDATE dbo.warehouse 
SET Label Label 
WHERE Label NOT NULL;

但这没用。

有人有什么想法或线索如何实现这一目标吗?

谢谢。

2 个答案:

答案 0 :(得分:1)

您可以使用FIRST_VALUE

WITH cte AS (
  SELECT *,
    label_2  = FIRST_VALUE(label)  OVER(PARTITION BY itemno ORDER BY id),
    series_2 = FIRST_VALUE(series) OVER(PARTITION BY itemno ORDER BY id),
    amount_2 = FIRST_VALUE(amount) OVER(PARTITION BY itemno ORDER BY id)
  FROM warehouse
)
UPDATE cte
SET label = label_2,
    series = series_2,
    amount = amount_2
WHERE label IS NULL
  AND series IS NULL
  AND Amount IS NULL;

答案 1 :(得分:0)

这只是连接的更新,如果需要,请检查其他列,我只检查两个表中的#include <array> #include <iostream> template <int I> struct power2 { enum { value = (1 << I) }; }; template <int N> class log2arr { private: using arrT = std::array<int, N>; arrT arr {}; template <int I, typename = std::true_type> struct log2 { log2<I-1> _arr; enum { value = log2<I-1>::value + (power2<log2<I-1>::value>::value == I) }; void print () { _arr.print(); std::cout << value << std::endl; } void set (arrT & a) { _arr.set(a); a[I] = value; } }; template <int I> struct log2<I, std::integral_constant<bool, I == 1>> { enum { value = 1 }; void print() {} void set(arrT &) {} }; public: log2arr () { log2<N>().set(arr); } arrT & getArr () { return arr; } arrT const & getArr () const { return arr; } }; int main () { log2arr<4> a; for ( auto i : a.getArr() ) std::cout << i; std::cout << std::endl; }

Label

结果:

CREATE TABLE T
(
   ID INT IDENTITY (1, 1) NOT NULL,
   ItemNo INT,
   Label VARCHAR(25),
   Series VARCHAR(25),
   Amount INT
);

INSERT INTO T (ItemNo, Label, Series, Amount) VALUES
(111, 'Baer', 'Toys', 9),
(111, NULL, NULL, NULL),
(222, 'Flower', 'Garden', 8),
(222, NULL, NULL, NULL),
(222, NULL, NULL, NULL);

UPDATE T1
SET T1.Label  = T2.Label,
    T1.Series = T2.Series,
    T1.Amount = T2.Amount
FROM T T1 INNER JOIN T T2 ON T1.ItemNo = T2.ItemNo AND T2.Label IS NOT NULL 
WHERE T1.Label IS NULL;

SELECT *
FROM T;