0

Hi I have a table that looks something like this:

Date ID Value
1/1/2011 id1 10
1/2/2011 id1 NULL
1/3/2011 id1 20
1/1/2011 id2 20
1/3/2011 id2 NULL
1/4/2011 id2 30

My task is to forward fill the values for each id and date until a new value becomes known. For example, I would like to insert the value 10 on 1/2/2011 for id1 and the value 20 on 1/3/2011 for id2. I am using mysql. Any help on this would be greatly appreciated.

1 Answer 1

0

In mysql, there really isn't any super-efficient way to make this happen (that I can think of) but it could be accomplished using a correlated subquery:

UPDATE table 
    SET value = (SELECT value 
                 FROM Table AS T1 
                 WHERE T1.ID = table.ID 
                     and t1.DATE <= table.Date 
                 LIMIT 1)
WHERE table.Value IS NULL; 

This assumes I'm interpreting the logic correctly. Let me know if this is the right idea.

10
  • yes, this is kind of what i had in mind too but in my (extremely short) experience with mysql, subqueries don't seem to return in any reasonable amount of time.. let me give this a shot! thank you for getting back to me so quickly.
    – Alex
    Nov 3, 2011 at 1:43
  • hmm, it looks like i get the following error: ERROR 1093 (HY000): You can't specify target table 'blah2' for update in FROM clause. i'm assuming this means that my subquery can't have the same table in it that my update clause has?
    – Alex
    Nov 3, 2011 at 1:49
  • just duplicated the table to get around that problem, we'll see if this thing returns
    – Alex
    Nov 3, 2011 at 2:11
  • Oh yeah. How I love MySQL sometimes. Subqueries aren't necessarily bad but this type, where it has to be evaluated for each row, can be really bad. Nov 3, 2011 at 2:55
  • hmm, any other thoughts? it looks like this has run for about 10 hours or so... the table is only 8 mil rows.. sort of disappointing at how slow mysql is being.
    – Alex
    Nov 3, 2011 at 14:55

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.