Update column with another value from the same table?

橙三吉。 提交于 2019-12-12 15:26:54

问题


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.


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/3506728/update-column-with-another-value-from-the-same-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!