在SQL Server中,我試圖用表中現有的值更新表中的空字段。更新字段 - SQL Server
實施例:
表有4列:A,B,C,d
A B C D
1 2 3 4
5 Null Null 4
如何可以填充在乙與值Null值,C是d = 4
Update Table
Set B=B
Where B is null
and D=4
在SQL Server中,我試圖用表中現有的值更新表中的空字段。更新字段 - SQL Server
實施例:
表有4列:A,B,C,d
A B C D
1 2 3 4
5 Null Null 4
如何可以填充在乙與值Null值,C是d = 4
Update Table
Set B=B
Where B is null
and D=4
一種選擇是使用self join
:
update t
set t.b = t2.b
from yourtable t
join yourtable t2 on t.d = t2.d
and t2.b is not null
where t.b is null
如果存在多個記錄,按b分組,那麼b在哪裏b不爲空?這可能會搞砸了。相反,你必須決定使用哪個值。下面是選擇一個例子min
:
update t
set t.b = t2.b
from yourtable t
join (select d, min(b) b
from yourtable
where b is not null
group by d) t2 on t.d = t2.d
where t.b is null
或者與相關子查詢:
update yourtable t
set b = (select min(b) from yourtable t2 where t.id = t2.id)
where t.b is null
很多在這裏的選項...
我不完全明白的問題:你在更新空值到什麼? B和C是空的。你希望他們從行A1複製到A5?爲此,我們可能需要更多的上下文。你可以做一個滯後和基於秩序,並像這樣填充它,但是如果你在連續行中有2個空值,那麼它會中斷 – LordBaconPants