Skip to content
Advertisement

Populating rows in table with previous row value oracle sql

+----+---------+-------+--------+---------+--------+
| id | counter | name  | duties | remarks | monies |
+----+---------+-------+--------+---------+--------+
|  1 |       1 | jake  |        |         |        |
|  2 |       0 |       | clean  | misc    | 12k    |
|  3 |       1 | james |        |         |        |
|  4 |       0 |       | clean  | misc    | 12k    |
|  5 |       0 |       | soap   | misc    | 12k    |
|  6 |       0 |       | shower | misc    | 12k    |
|  7 |       1 | john  |        |         |        |
|  8 |       0 |       | dry    | misc    | 12k    |
|  9 |       0 |       | scrub  | misc    | 12k    |
+----+---------+-------+--------+---------+--------+

Here above the data is grouped by person then their duties are listed :

I need a way to get the data to look like this using oracle sql :

+----+---------+-------+--------+---------+--------+
| id | counter | name  | duties | remarks | monies |
+----+---------+-------+--------+---------+--------+
|  1 |       1 | jake  |        |         |        |
|  2 |       0 | jake  | clean  | misc    | 12k    |
|  3 |       1 | james |        |         |        |
|  4 |       0 | james | clean  | misc    | 12k    |
|  5 |       0 | james | soap   | misc    | 12k    |
|  6 |       0 | james | shower | misc    | 12k    |
|  7 |       1 | john  |        |         |        |
|  8 |       0 | john  | dry    | misc    | 12k    |
|  9 |       0 | john  | scrub  | misc    | 12k    |
+----+---------+-------+--------+---------+--------+

having a bit of trouble iterating over every row… dont mind if its plsql – sql prefered tho

Tried a few things… but it goes back to null after the 2nd row for each person

Advertisement

Answer

One method is lag(ignore nulls):

select coalesce(name, lag(name ignore nulls) over (order by id)),
       . . .
from t;

This is fetching the previous non-NULL value from the name columns, where “previous” is based on the ordering of the id column.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement