SQL的新手,给我带来了以下问题。很抱歉,这是一个简单的解决方法。我今天早上看的所有替换问题似乎都不能解决这个确切的问题。
我正在使用SQL Server 2017,并且具有类似于以下内容的表,实际表为100k +行,但遵循这种格式,它只包含更多的单独项和列:
ColA ColB ColC ColD ColE ColF
---- ---- ---- ---- ---- ----
ROW1 Item1 2341 Null Null Null
ROW2 Item2 7953 Null Null Null
ROW3 Item1 Null 2342 Null Null
ROW4 Item2 Null 9827 Null Null
ROW5 Item1 Null Null 1945 Null
ROW6 Item2 Null Null 0745 Null
ROW7 Item1 Null Null Null 1298
ROW8 Item2 Null Null Null 2356
是否可以通过编程方式更新表,以使ROW1和ROW2具有D,E和F列的所有非NULL值?
答案 0 :(得分:0)
这2条语句应该可以帮助您。如果仅在SELECT
语句之后,则第一个是您要执行的语句。如果您想实际UPDATE
的所有行,那么您需要具有CTE的行:
USE Sandbox;
GO
CREATE TABLE dbo.Tab (ColA char(4),
ColB char(5),
ColC char(5),
ColD char(5),
ColE char(5),
ColF char(5));
INSERT INTO dbo.Tab (ColA,
ColB,
ColC,
ColD,
ColE,
ColF)
VALUES('ROW1','Item1',2341,Null,Null,Null),
('ROW2','Item2',7953,Null,Null,Null),
('ROW3','Item1',Null,2342,Null,Null),
('ROW4','Item2',Null,9827,Null,Null),
('ROW5','Item1',Null,Null,1945,Null),
('ROW6','Item2',Null,Null,0745,Null),
('ROW7','Item1',Null,Null,Null,1298),
('ROW8','Item2',Null,Null,Null,2356);
GO
SELECT ColA,
ColB,
MAX(ColC) OVER (PARTITION BY ColB) AS ColC,
MAX(ColD) OVER (PARTITION BY ColB) AS ColD,
MAX(ColE) OVER (PARTITION BY ColB) AS ColE,
MAX(ColF) OVER (PARTITION BY ColB) AS ColF
FROM dbo.Tab
ORDER BY ColB;
GO
WITH CTE AS(
SELECT ColA,
ColB,
ColC,
ColD,
ColE,
ColF,
MAX(ColC) OVER (PARTITION BY ColB) AS ColCn,
MAX(ColD) OVER (PARTITION BY ColB) AS ColDn,
MAX(ColE) OVER (PARTITION BY ColB) AS ColEn,
MAX(ColF) OVER (PARTITION BY ColB) AS ColFn
FROM dbo.Tab)
UPDATE CTE
SET ColC = ColCn,
ColD = ColDn,
ColE = ColEn,
ColF = ColFn;
GO
SELECT *
FROM Tab;
GO
DROP TABLE dbo.Tab;