2

I am trying to create a query that will populate all null values in a dataset with the last known value (123 in this case).

datetime          value
01/SEP/18 00:30   111
01/SEP/18 00:35   122
01/SEP/18 00:40   101
01/SEP/18 00:45   123
01/SEP/18 00:50   NULL
01/SEP/18 00:55   NULL
01/SEP/18 13:00   NULL
...
...
...
01/SEP/18 23:55   NULL

The end result table should look like this

datetime          value
01/SEP/18 00:30   111
01/SEP/18 00:35   122
01/SEP/18 00:40   101
01/SEP/18 00:45   123
01/SEP/18 00:50   123
01/SEP/18 00:55   123
01/SEP/18 13:00   123
...
...
...
01/SEP/18 23:55   123
1
  • You should remove your answer from the question and add it as a separate answer, so that you can mark that as the accepted answer. That way, your question is more likely to help future StackOverflow users when they come across your question. Commented Sep 27, 2018 at 8:18

2 Answers 2

1

You could use an update with a correlated subquery:

UPDATE yourTable t1
SET value = (SELECT value
             FROM   (SELECT value, ROWNUM AS rn
                     FROM yourTable t2
                     WHERE t2.datetime < t1.datetime AND t2.value IS NOT NULL
                     ORDER BY datetime DESC)
             WHERE  rn = 1)
WHERE value IS NULL;

The idea behind this update is to find, using a subquery, the most recent value which is not NULL, which is nearest to a given missing value.

If you instead wanted to just select your current table to generate the expected output, you could try:

SELECT
    datetime,
    CASE WHEN value IS NULL
         THEN (SELECT value
               FROM   (SELECT value, ROWNUM AS rn
                       FROM yourTable t2
                       WHERE t2.datetime < t1.datetime AND t2.value IS NOT NULL
                       ORDER BY datetime DESC)
               WHERE  rn = 1)
         ELSE value END AS value
FROM yourTable t1;
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for you response. I probably was not clear enough with the question. But your response has set me on the right path. I have updated my initial post with the query I propose to use. One of the limitations is that I cannot do any updates.
You can convert my update into a select. Didn't know about LAST_VALUE; that seems like maybe a better option.
0

I managed to get the desired result with the following query:

  SELECT DATETIME, VALUE, last_value(VALUE) ignore nulls over (order by DATETIME) 
  FROM
  TABLE1;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.