Set based solution to update nulls to Last Known Value in ordered table
-
30-10-2019 - |
문제
To maintain my purity and honor as a database dork, I wish to update a set of datetimes and floats that has some nulls in the float column such that each null value will be replaced by the previous (by datetime) non-null value.
My environment is mssql 2k8R2.
I hope the following snippet explains my victory conditions sufficiently.
Cheers and Thanks.
create table #datesAndValues(
[Date] datetime,
Val float);
create table #resultsShouldLookLikeThis(
[Date] datetime,
Val float);
insert into #datesAndValues
values
('1/8/11',1.1),
('1/7/11',null),
('1/6/11',1.2),
('1/5/11',null),
('1/4/11',null),
('1/3/11',1.3),
('1/2/11',null),
('1/1/11',null);
/*
set based code (no loops!!!) goes here to set nulls
in the above table to the last known good (not null) value,
thereby making it look like the following table.
*/
insert into #resultsShouldLookLikeThis
values
('1/8/11',1.1),
('1/7/11',1.2),
('1/6/11',1.2),
('1/5/11',1.3),
('1/4/11',1.3),
('1/3/11',1.3),
('1/2/11',null),
('1/1/11',null);
--this will tell us if it worked
select 'In old but not new' as [WhichTable], o.*
from (select * from #datesAndValues
except select * from #resultsShouldLookLikeThis) o
union all
select 'In new but not old' as [WhichTable], n.*
from (select * from #resultsShouldLookLikeThis
except select * from #datesAndValues) n;
drop table #datesAndValues;
drop table #resultsShouldLookLikeThis;
올바른 솔루션이 없습니다
제휴하지 않습니다 StackOverflow