mysql - How can I fill empty cells with values from previous rows -
i have table looks following example. i'd replcae missing value (if any) in column previous value. table:
col1 col2 0.1 0.2 0.23 0.53 - 0.46 0.77 - - 0.32
i expect following results:
col1 col2 0.1 0.2 0.23 0.53 0.23 0.46 0.77 0.46 0.77 0.32
in order this, you'll need sort of identifier previous row. hypothetically (since waiting clarification on 'previous' in example), let's have primary key identifier each row:
| id | col1 | col2 | +----+------+------+ | 1 | 0.1 | 0.2 | | 2 | 0.23 | 0.53 | | 3 | null | 0.46 | | 4 | 0.77 | null | | 5 | null | 0.32 |
you can use value previous primary key update table. can join
2 tables on condition id matches previous one, , set col1 value accordingly this:
update mytable m join mytable mt on (m.id - 1) = mt.id set m.col1 = mt.col1 m.col1 null;
to both columns in same update query, you'll need add if
statement:
update mytable m join mytable mt on (m.id - 1) = mt.id set m.col1 = case when m.col1 null mt.col1 else m.col1 end, m.col2 = case when m.col2 null mt.col2 else m.col2 end;
here reference on conditional update, , sql fiddle example. can't run query, build schema option. edit answer results when can.
note not work if there 2 null values in row. if possible, need join rows on recent non-null id.
Comments
Post a Comment