2010-08-17 148 views
3

的設置是這樣的:使用同一個表中的另一個值更新列?

Col1  Col2 
12345  12 
12348  14 
20145  16 
00541  Null 
51234  22 

簡化,效果顯着。我想要做的就是更新Col2,無論它在哪裏都是Null,通過將它設置爲Col2值,使其在Col1中具有最接近的值(因此在本示例中,第四行應將Col2設置爲12)。這是多麼接近我已經得到:

UPDATE Temp.dbo.Sheet4 
    SET Col2 = (SELECT FIRST(Col2) 
       FROM Temp.dbo.Sheet4 
       WHERE Col2 IS NOT NULL 
      ORDER BY ABS(***Col1 from the outside of this select statement*** - Col1)) 
WHERE Col2 IS NULL 

可能不那麼接近。但我該怎麼做?我無法理解我的頭腦。我也願意在Excel/Access /中做到這一點,但我認爲SQL Server會是最簡單的。

回答

3

這是一種很難嘗試了這一點,而不建立數據庫,但工作的呢?

UPDATE sh 
    SET sh.Col2 = (SELECT TOP 1 sh_inner.Col2 
       FROM Temp.dbo.Sheet4 sh_inner 
       WHERE sh_inner.Col2 IS NOT NULL 
      ORDER BY ABS(sh.Col1 - sh_inner.Col1)) 
FROM Temp.dbo.Sheet4 sh 
WHERE sh.Col2 IS NULL 
+0

工程就像一個魅力。謝謝! – extarbags 2010-08-17 21:11:47

1

馬丁,

工程。這裏有一個使用你的解決方案的例子:

create table #junk 
(col1 int, col2 int) 

insert #junk 
values(12345,12), 
(12348,14), 
(20145,16), 
(541,null), 
(51234,22) 

update j 
    set col2 = (select top 1 j2.col2 from #junk j2 where j2.col2 is not null order by ABS(j.col1-j2.col1)) 
from #junk j where col2 is null 

select * from #junk 
drop table #junk 
相關問題