For example I have a dataset like the following:
| time | action |
|---|---|
| 03:00:00 | block |
| 04:00:00 | unblock |
| 05:00:00 | block |
| 06:00:00 | unblock |
| 07:00:00 | unblock |
| 08:00:00 | block |
Now for each row, I want to get the last time when the column action equals to "block" before the time of current row. For example, for the fifth row whose time equals to "07:00:00" and action equals to "unblock", the last time before it when action equals to "block" should be the third row, and the expected time is "05:00:00".
My final expected result would be:
| time | action | last_time |
|---|---|---|
| 03:00:00 | block | 03:00:00 |
| 04:00:00 | unblock | 03:00:00 |
| 05:00:00 | block | 05:00:00 |
| 06:00:00 | unblock | 05:00:00 |
| 07:00:00 | unblock | 05:00:00 |
| 08:00:00 | block | 08:00:00 |
How can I get the above result by using a window function without joining by itself?
(p.s. if the above result cannot be reached, the following output is also okay:
| time | action | last_time |
|---|---|---|
| 03:00:00 | block | NULL |
| 04:00:00 | unblock | 03:00:00 |
| 05:00:00 | block | 03:00:00 |
| 06:00:00 | unblock | 05:00:00 |
| 07:00:00 | unblock | 05:00:00 |
| 08:00:00 | block | 05:00:00 |