2

我的桌子看起来像这样

Id Description
5  Null
4  This is a description
3  This is a description
2  Null
1  Null

我需要创建一个更新语句,如果前一个值不为空,它将更新空值。

Id Description
5  This is a description
4  This is a description
3  This is a description
2  Null
1  Null

任何建议或帮助将不胜感激。

4

2 回答 2

2

我想这就是你要找的:

update toupdate
set description = updateto.description 
from yourtable toupdate
  join yourtable updateto on updateto.id = toupdate.id - 1
where updateto.description is not null
  and toupdate.description is null;

SQL 小提琴演示

这会产生以下结果:

ID  DESCRIPTION
5   This is a description
4   This is a description
3   This is a description
2   (null)
1   (null)

编辑:正如 Aaron Bertrand 的评论所指出的。

如果您的 ID 不连续,您可以使用row_number()函数加入而不是 id:

with cte as (
    select *, row_number() over (order by (select null)) rn
    from yourtable
  )
update toupdate
set description = updateto.description 
from cte toupdate
  join cte updateto on toupdate.rn = updateto.rn - 1
where updateto.description is not null
  and toupdate.description is null;

您可以根据需要按标准更改订单。

更新的 SQL Fiddle

于 2013-04-02T01:20:11.750 回答
1

做这种事情的最常见方法(我知道)是使用自联接:

-- WARNING: Untested Code
UPDATE YourTable
SET Origin.Description = Proxy.Description
FROM YourTable Origin
JOIN YourTable Proxy
    ON Origin.Id = Proxy.Id - 1
WHERE Origin.Description IS NULL
AND Proxy.Description IS NOT NULL

这将连接YourTable到自身,因此一行看起来像这样:

Origin.Id | Origin.Description | Proxy.Id | Proxy.Description
------------------------------------------------------------------
        5 |               NULL |        4 | This is a description

编辑
如果您不能保证总是递增 ID,那么您将要使用ROW_NUMBER

;WITH NumberedRows
AS
    (
    SELECT *
        , ROW_NUMBER() OVER(ORDER BY Id) AS [Row #]
     FROM YourTable
     )
SELECT *
FROM NumberedRows Origin
JOIN NumberedRows Proxy
    ON Origin.Id = Proxy.Id - 1
WHERE Origin.Description IS NULL
AND Proxy.Description IS NOT NULL
于 2013-04-02T01:12:56.430 回答