I have a table p1 with transactions in Postgres like this:
| id | product_id | transaction_date | quantity |
|----|------------|------------------|----------|
| 1  | 1          | 2015-01-01       | 1        |
| 2  | 1          | 2015-01-02       | 2        |
| 3  | 1          | 2015-01-03       | 3        |
and p2 table with products like this:
| id | product      | stock |
|----|--------------|-------|
| 1  | Product A    | 15    |
stock in p2' has been be reduced for every new record in p1.
How to reconstruct previous states to get this result?
| product   | first_stock | quantity | last_stock |
|-----------|-------------|----------|------------|
| Product A | 21          | 1        | 20         |
| Product A | 20          | 2        | 18         |
| Product A | 18          | 3        | 15         |
I have tried using lead() to get the quantity after the current row.
SELECT p2.product, p1.quantity, lead(p1.quantity) OVER(ORDER BY p1.id DESC)
FROM p1 INNER JOIN p2 ON p1.product_id = p2.id;
But how to calculate leading rows from the current stock?