Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 Replace null value with previous non-null value

Author  Topic 

Kurmanc
Yak Posting Veteran

92 Posts

Posted - 2010-09-22 : 11:09:23
If you use the code below you will see that obsvalue is not 106 for 2010-01-08 and 2010-01-09. Can anyone help me out..I started out ok but not entirely. What can I do to fix this small issue? The result should show a replacement of null values with previous non-null value.

Thanks in advance.


create table test
(
obsdate datetime,
obsvalue int
)

insert into test(obsdate, obsvalue)
select '2010-01-01', 100
union
select '2010-01-02', 101
union
select '2010-01-03', null
union
select '2010-01-04', null
union
select '2010-01-05', 104
union
select '2010-01-06', 105
union
select '2010-01-07', 106
union
select '2010-01-08', null
union
select '2010-01-09', null
union
select '2010-01-10', 109


declare @from datetime
declare @to datetime
declare @minDate datetime
declare @latestKnownObsValue int
--set @from = '2010-01-03'
--set @to = '2010-01-05'
--set @from = '2010-01-01'
--set @to = '2010-01-06'
set @from = '2010-01-01'
set @to = '2010-01-10'

select * from test

--for this result, find the previous non-null value replace with the null value
select obsdate, obsvalue
from test
where obsdate between @from and @to

select @minDate=min(obsdate)
from test
where obsvalue is null
and obsdate between @from and @to

select @latestKnownObsValue=max(obsvalue)
from test
where obsdate < @minDate

select obsdate, isnull(obsvalue ,@latestKnownObsValue) as obsvalue
from test
where obsdate between @from and @to

Transact Charlie
Master Smack Fu Yak Hacker

3451 Posts

Posted - 2010-09-22 : 11:23:18
Try this

SELECT
t.[obsdate]
, ISNULL(t.[obsvalue], pVal.[obsvalue]) AS [obsvalue]
FROM
test AS t

OUTER APPLY (
SELECT TOP 1
[obsvalue] AS [obsvalue]
FROM
test AS t2
WHERE
t2.[obsvalue] IS NOT NULL
AND t2.[obsDate] < t.[obsDate]
ORDER BY
t2.[obsDate] DESC
)
AS pVal
WHERE
obsdate BETWEEN @from AND @to


Charlie
===============================================================
Msg 3903, Level 16, State 1, Line 1736
The ROLLBACK TRANSACTION request has no corresponding BEGIN TRANSACTION
Go to Top of Page

Kurmanc
Yak Posting Veteran

92 Posts

Posted - 2010-09-22 : 11:29:27
Transact Charlie,

Works perfectly!

Thanks my friend!
Go to Top of Page
   

- Advertisement -