基于以前的值SQL SERVER 2005进行更新

时间:2014-09-03 02:46:30

标签: sql sql-server sql-server-2005 sql-update logic

我需要更新这些NULL值:

PK |  CODE
---+-------
1  |   20
2  |   NULL
3  |   NULL
4  |   30
5  |   NULL
6  |   NULL
7  |   NULL
8  |   40
9  |   NULL

像这样:

PK   |   CODE
-----+------------
1    |    20
2    |    20
3    |    20
4    |    30
5    |    30
6    |    30
7    |    30
8    |    40
9    |    40

它应该始终基于最后的最小值。

我已尝试过下面的代码,但它只更新了开头有价值的那一行之前的第一行。

QUERY

UPDATE TT 
SET CODE = (SELECT CODE 
FROM #TSPV_TEMP T2 with(nolock)
WHERE T2.KEY = (tt.KEY -1))
FROM #TSPV_TEMP TT with (nolock)
WHERE tt.CODE IS NULL

3 个答案:

答案 0 :(得分:2)

您可以这样做:

UPDATE TT 
    SET CODE = (SELECT TOP 1 CODE
                FROM #TSPV_TEMP T2 with(nolock)
                WHERE T2.KEY < tt.KEY AND
                      CODE IS NOT NULL
                ORDER BY KEY DESC
               )
    FROM #TSPV_TEMP TT with (nolock)
    where tt.CODE IS NULL;

请注意子查询中的差异。这将查找更新的CODE之前的非NULL值。

答案 1 :(得分:0)

update tbl
   set code =
       (select code
          from tbl x
         where x.pk = (select max(y.pk)
                         from tbl y
                        where y.pk < tbl.pk
                          and code is not null))
 where code is null;

<强>小提琴: http://sqlfiddle.com/#!3/3803d/1/0

答案 2 :(得分:0)

另一种使用派生表的方法,对于每个具有空代码的pk,它包含具有非空代码的最小pk。

update t1
set t1.code = t3.code
from tt t1 join
    (select t1.pk, max(t2.pk) max_pk
    from tt t1
    join tt t2 on t1.pk > t2.pk
    and t2.code is not null
    and t1.code is null
    group by t1.pk) t2 on t2.pk = t1.pk
join tt t3 on t3.pk = t2.max_pk