[英]Update based on previous value SQL SERVER 2005
I need to Update these NULL Values: 我需要更新这些NULL值:
PK | CODE
---+-------
1 | 20
2 | NULL
3 | NULL
4 | 30
5 | NULL
6 | NULL
7 | NULL
8 | 40
9 | NULL
Like this: 像这样:
PK | CODE
-----+------------
1 | 20
2 | 20
3 | 20
4 | 30
5 | 30
6 | 30
7 | 30
8 | 40
9 | 40
It should always be based on the last minimum value. 它应始终基于最后的最小值。
I have tried the code below, but it just updates the first row before the one who had value at the beginning. 我已经尝试了下面的代码,但它只更新了在开头有价值的那一行之前的第一行。
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
You can do this as: 你可以这样做:
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;
Note the differences in the subquery. 请注意子查询中的差异。 This looks for the previous non-NULL value for
CODE
for the update. 这将查找更新的
CODE
的先前非NULL值。
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;
Fiddle: http://sqlfiddle.com/#!3/3803d/1/0 小提琴: http ://sqlfiddle.com/#!3/3803d/1/0
Another way using a derived table which for every pk with a null code contains the maximum lesser pk with a non-null code. 使用派生表的另一种方法,对于具有空代码的每个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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.