2016-03-08 97 views
0

在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 
+0

我不完全明白的問題:你在更新空值到什麼? B和C是空的。你希望他們從行A1複製到A5?爲此,我們可能需要更多的上下文。你可以做一個滯後和基於秩序,並像這樣填充它,但是如果你在連續行中有2個空值,那麼它會中斷 – LordBaconPants

回答

1

一種選擇是使用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 

很多在這裏的選項...

+0

我想更新d是相同的空字段。如果3條記錄的D = 4,則b和c中的值可能不同,但我希望它們出現在其中D = 4的列b和c中的任何行中。 – Jeff

+0

@Jeff - 所有這些查詢都是這樣做的......如果'd'是相同的,但有多個不是'null'的'b'值?你使用哪個值?這就是這個答案試圖解決你的問題。取決於你想要做什麼。這些選項應該儘可能接近。 – sgeddes

+0

我會試試看,現在就讓你。感謝您的幫助。 – Jeff