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.
Author |
Topic |
Umar Strong
Starting Member
8 Posts |
Posted - 2013-07-31 : 17:46:25
|
Is it possible to write a query to fill in the missing value of a column with the last known value.For example, the following dataset has values for the years 2010,11,12,15 & 16; but does have values for the year 2013,14 & 18.Year Value---- ------2010 A2011 B2012 C2013 20142015 P2016 Q2018 My requirement is to fill in the missing values with the last known values - i.e.,Year Value---- ------2010 A2011 B2012 C2013 C2014 C2015 P2016 Q2018 QCan this be done using a SQL? I have tried using self join to the table i.e., INNER JOIN and OUTER APPLY. But I guess I am not writing the query correctly. |
|
Umar Strong
Starting Member
8 Posts |
Posted - 2013-07-31 : 18:09:11
|
I just solved it using APPLY.DDL/DML:CREATE TABLE DBO.TEMP_RND ([YEAR] INT, [VALUE] VARCHAR(1))INSERT INTO DBO.TEMP_RND VALUES (2010, 'A')INSERT INTO DBO.TEMP_RND VALUES (2011, 'B')INSERT INTO DBO.TEMP_RND VALUES (2012, 'C')INSERT INTO DBO.TEMP_RND VALUES (2013, NULL)INSERT INTO DBO.TEMP_RND VALUES (2014, NULL)INSERT INTO DBO.TEMP_RND VALUES (2015, 'P')INSERT INTO DBO.TEMP_RND VALUES (2016, 'Q')INSERT INTO DBO.TEMP_RND VALUES (2018, NULL)SQL:SELECT a.[YEAR], COALESCE(a.[VALUE], b.[VALUE]) AS FILLED_IN_VALUEFROM TEMP_RND a OUTER APPLY ( SELECT TOP 1 x.[VALUE] FROM TEMP_RND x WHERE a.[VALUE] IS NULL AND x.[VALUE] IS NOT NULL AND x.[YEAR] < a.[YEAR] ORDER BY x.[YEAR] DESC ) b |
|
|
|
|
|
|
|