I have a table with the following structure:
| id | col1 | col2 |
|---|---|---|
| 1 | 1 | 0 |
| 2 | 1 | 1 |
| 3 | 1 | 0 |
| 4 | 1 | 2 |
| 5 | 1 | 1 |
| 6 | 1 | 2 |
| 7 | 1 | 1 |
I would like to get the following result:
| id | col1 | col2 | col3 |
|---|---|---|---|
| 1 | 1 | 0 | 1 |
| 2 | 1 | 1 | 1 |
| 3 | 2 | 0 | 3 |
| 4 | 0 | 2 | 1 |
| 5 | 3 | 1 | 3 |
| 6 | 0 | 2 | 1 |
| 7 | 0 | 1 | 0 |
where col3= col3 value of previous row + col1 value - col2 value
I added a column of zeroes like this:
| id | col1 | col2 | col3 |
|---|---|---|---|
| 1 | 1 | 0 | 0 |
| 2 | 1 | 1 | 0 |
| 3 | 2 | 0 | 0 |
| 4 | 0 | 2 | 0 |
| 5 | 3 | 1 | 0 |
| 6 | 0 | 2 | 0 |
| 7 | 0 | 1 | 0 |
and tried the following query:
select col1, col2,
lag(col3) over (order by id) + col1 - col2 as col3
from t1;
However I am not able to obtain the desired result. I would like to get some help with this.