Mike Osborne (1/10/2014)
I would like an efficient way to "fill missing data".My preference would be a view.
I have data like:
Date, A, B
1/1/2013 5 99
1/2/2013 null 99
1/3/2013 6 null
1/4/2013 null null
1/5/2013 7 98
1/6/2013 null null
and view results:
Date, A, B
1/1/2013 5 99
1/2/2013 5 99
1/3/2013 6 99
1/4/2013 6 99
1/5/2013 7 98
1/6/2013 7 98
etc...you get the idea
caution: there are about a million rows in the raw table
Mike O.
You're kind of new here so a couple of hints, first.
Always post in the correct form. I don't know why you posted this in a 2000 forum and it only led to some confusion.
If you want coded answers, please see the first link under "Helpful Links" in my signature line below.
I'll take care of that this time because you're new.
Here's the kind of code that I was talking about. It actually has to hit the table 3 times. While it can be made to work fairly quickly, it just seems unnecessary since the original data will never change. You could even make a sister table to hold prefilled columns and keep them updated with a well written trigger.
DROP TABLE #TestTable
GO
--===== Create the test table (not a part of the solution)
CREATE TABLE #TestTable
(
Date DATETIME NOT NULL PRIMARY KEY CLUSTERED
,A INT
,B INT
)
;
--===== Populate the table with test data (not a part of the solution)
INSERT INTO #TestTable
SELECT '1/1/2013',5 ,99 UNION ALL
SELECT '1/2/2013',null,99 UNION ALL
SELECT '1/3/2013',6 ,null UNION ALL
SELECT '1/4/2013',null,null UNION ALL
SELECT '1/5/2013',7 ,98 UNION ALL
SELECT '1/6/2013',null,null
;
--===== Solve the problem using conventional means
SELECT tt.Date
,a.A
,b.B
FROM #TestTable tt
CROSS APPLY (SELECT TOP 1 tta.A FROM #TestTable tta WHERE tta.Date <= tt.Date AND tta.A IS NOT NULL ORDER BY tta.Date DESC)a(A)
CROSS APPLY (SELECT TOP 1 ttb.B FROM #TestTable ttb WHERE ttb.Date <= tt.Date AND ttb.B IS NOT NULL ORDER BY ttb.Date DESC)b(B)
ORDER BY tt.Date
;
Result set for the currently provided data and problem definition...
Date A B
----------------------- ----------- -----------
2013-01-01 00:00:00.000 5 99
2013-01-02 00:00:00.000 5 99
2013-01-03 00:00:00.000 6 99
2013-01-04 00:00:00.000 6 99
2013-01-05 00:00:00.000 7 98
2013-01-06 00:00:00.000 7 98
(6 row(s) affected)
--Jeff Moden
Change is inevitable... Change for the better is not.