1

我有类似以下脚本的数据。我想用同一列的数据更新空列,但在同一列中任何不为空的行。

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 表中阅读此内容。如果这是不可能的,那么我可以要求用户在 Excel 工作表的第一列中添加一个行号,如 ID。那会奏效吗?

谢谢!

4

2 回答 2

1

表中的条目是无序的,所以这是不可能的,除非你自己定义一个订单(用 "order by" )

于 2013-03-06T11:21:55.940 回答
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上的演示

于 2013-03-06T11:22:48.003 回答