开发者

Update column with another value from the same table?

The setup is like this:

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

Simplified, obviously. What I want to do is update Col2 wherever it's Null by setting it to the Col2 value for whatever has the closest value in Col1 (so in this example, row four should have Col2 set to 12). This is how close I've gotten:

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

Probably not that close. But how can I do this? I can'开发者_高级运维t quite get my head around it. I'm also open to doing this in Excel/Access/whatever, but I figured SQL Server would be the easiest.


It is kind of hard to try this out without the database set up, but does this work?

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


Martin,

That works. Here's an example using your solution:

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜