I have a requirement to fetch previous row or lag records where there are some missing previous ids.
Database : Oracle 12c
Example data:
| BRANCH | PERIOD | QTY |
|---|---|---|
| 105 | 319 | 17 |
| 105 | 320 | 20 |
| 105 | 321 | 32 |
| 105 | 322 | 61 |
| 107 | 319 | 17 |
| 107 | 321 | 18 |
| 107 | 322 | 16 |
| 108 | 319 | 21 |
| 108 | 322 | 27 |
I want the results in below format: If you see for branch 107 : the period 319 is missing and for branch 108 : 320,321 are missing. So if there are any missing previous records then the prev_period_<>_Qty columns should be 0.
Can you please help in achieving this.
| BRANCH | PERIOD | QTY | PREV_PERIOD_1_QTY | PREV_PERIOD_2_QTY | PREV_PERIOD_3_QTY |
|---|---|---|---|---|---|
| 105 | 319 | 17 | 0 | 0 | 0 |
| 105 | 320 | 20 | 17 | 0 | 0 |
| 105 | 321 | 32 | 20 | 17 | 0 |
| 105 | 322 | 61 | 32 | 20 | 17 |
| 107 | 319 | 17 | 0 | 0 | 0 |
| 107 | 321 | 18 | 0 | 17 | 0 |
| 107 | 322 | 16 | 18 | 0 | 17 |
| 108 | 319 | 21 | 0 | 0 | 0 |
| 108 | 322 | 27 | 0 | 0 | 21 |
From Oracle 12, you can use
MATCH_RECOGNIZEto do row-by-row processing:Or, using
LAG:Which, for the sample data:
Both output:
db<>fiddle here