使用具有NULL以上任何行中的数据的相同列更新NULL

时间:2013-03-06 11:06:21

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

我有跟随脚本的数据。我想用相同列的数据更新null列,但是在同一列中使用任何非空的行。

DECLARE @tbl TABLE(Country NVARCHAR(100), County NVARCHAR(100),
                     Street NVARCHAR(100), Name NVARCHAR(100))
INSERT INTO @tbl 
VALUES('England', 'County1', 'A Street', 'James'),
('', '', '', 'Deen'),
('', '', 'B Street', 'Adam'),
('', '', 'C Street', 'Max'),
('', 'County2', 'Y Street', 'Dax'),
('', '', '', 'Dax'),
('', '', '', 'Pax'),
('France', 'County i', 'Street ix', 'Chris'),
('', '', '', 'Crai'),
('', '', '', 'Adam')

更新后,表格应如下所示:

DECLARE @tbl TABLE(Country NVARCHAR(100), County NVARCHAR(100),
                     Street NVARCHAR(100), Name NVARCHAR(100))
INSERT INTO @tbl 
VALUES('England', 'County1', 'A Street', 'James'),
('England', 'County1', 'A Street', 'Deen'),
('England', 'County1', 'B Street', 'Adam'),
('England', 'County1', 'C Street', 'Max'),
('England', 'County2', 'Y Street', 'Dax'),
('England', 'County2', 'Y Street', 'Dax'),
('England', 'County2', 'Y Street', 'Pax'),
('France', 'County i', 'Street ix', 'Chris'),
('France', 'County i', 'Street ix', 'Crai'),
('France', 'County i', 'Street ix', 'Adam')

SELECT * FROM @tbl

我正在阅读Excel Sheet中的内容。如果这不可能,那么我可以要求用户在Excel工作表的第一列中添加ID等行号。那会有用吗?

谢谢!

2 个答案:

答案 0 :(得分:1)

表中的条目是无序的,所以除非您自己定义订单(使用“order by”),否则无法执行此操作

答案 1 :(得分:0)

您可以使用CTE选项

 ;WITH cte AS
 (
  SELECT *, ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS Id
  FROM tbl
  ), cte2 AS
 (
  SELECT Id, Country, County, Street, Name
  FROM cte
  WHERE Id = 1
  UNION ALL
  SELECT c.Id, COALESCE(c.Country, c2.Country), 
               COALESCE(c.County, c2.County), 
               COALESCE(c.Street, c2.Street), c.Name
  FROM cte c JOIN cte2 c2 ON  c.Id = c2.Id + 1
  )
  UPDATE c
  SET c.Country = c2.Country,
      c.County = c2.County,
      c.Name = c2.Name,
      c.Street = c2.Street
  FROM cte c JOIN cte2 c2 ON c.Id = c2.Id

SQLFiddle上的演示