| id | flow | amount | date |
|---|---|---|---|
| 1 | IN | 100 | 2023-08-01 |
| 2 | OUT | 100 | 2023-08-02 |
| 3 | IN | 100 | 2023-08-03 |
| 4 | OUT | 100 | 2023-08-04 |
| 5 | OUT | 100 | 2023-08-05 |
In a table like above, I want to sum all OUT transactions which take place after every IN transaction. The desired outcome should look like below:
| id | flow | amount | date | out_amount |
|---|---|---|---|---|
| 1 | IN | 100 | 2023-08-01 | 100 |
| 3 | IN | 100 | 2023-08-03 | 200 |
How could this be achieved?
If you are using Presto then you can follow gaps-and-islands approach (based on provided data I would use
idas ordering field, but for actual you might need/want to usedate):Output:
For Trino you can also use
MATCH_RECOGNIZE: