I came across this question in a round of interview. A table has the following column.
| ID |
|---|
| 1 |
| 2 |
| 3 |
| 4 |
| 5 |
| 6 |
| 7 |
| 8 |
| 9 |
| 11 |
| 12 |
| 13 |
| 14 |
| 15 |
| 16 |
| 17 |
| 18 |
| 19 |
| 20 |
| 22 |
| 23 |
| 24 |
| 26 |
The question is to create a new column that starts with '1' and increments on the next ID whenever there is a multiple of 5. So the expected output is
| ID | Result |
|---|---|
| 1 | 1 |
| 2 | 1 |
| 3 | 1 |
| 4 | 1 |
| 5 | 1 |
| 6 | 2 |
| 7 | 2 |
| 8 | 2 |
| 9 | 2 |
| 11 | 2 |
| 12 | 2 |
| 13 | 2 |
| 14 | 2 |
| 15 | 2 |
| 16 | 3 |
| 17 | 3 |
| 18 | 3 |
| 19 | 3 |
| 20 | 3 |
| 22 | 4 |
| 23 | 4 |
| 24 | 4 |
| 26 | 4 |
You can combine two window functions:
LAG()andSUM(). For example:Result:
See running example at DB Fiddle.