I have a very specific problem in T-SQL.
If I can solve this example case I give you I think I will be able to solve my original case.
Having this data in a table:
DECLARE @Test TABLE
(
Value INT
,Date DATETIME2(7)
);
INSERT INTO @Test
VALUES
(NULL, '2011-01-01 10:00'),
(NULL, '2011-01-01 11:00'),
(2, '2011-01-01 12:00'),
(NULL, '2011-01-01 13:00'),
(3, '2011-01-01 14:00'),
(NULL, '2011-01-01 15:00'),
(NULL, '2011-01-01 16:00'),
(4, '2011-01-01 17:00'),
(NULL, '2011-01-01 18:00'),
(5, '2011-01-01 19:00'),
(6, '2011-01-01 20:00')
I need to select this output:
Value Date
2 2011-01-01 10:00
2 2011-01-01 11:00
2 2011-01-01 12:00
2 2011-01-01 13:00
3 2011-01-01 14:00
3 2011-01-01 15:00
3 2011-01-01 16:00
4 2011-01-01 17:00
4 2011-01-01 18:00
5 2011-01-01 19:00
6 2011-01-01 20:00
To give some explanation. If value is NULL somewhere I need to update with the value from the previous hour. If there are several null values in a row the closest earlier hour with a non null value propagates and fills all these null values. Also if the first hour of the day is null then the earliest hour on the day with a non null value propagates downwards like 2 in this case. In your case you can assume that at least one value is non null value.
My ambition is to solve this with Common table expressions or something similar. With the cursor way I think I would have the solution in short bit of time if I try but my attempts with CTEs and recursive CTEs have failed so far.