Table product has average revenue by product
| product | avg_rev |
|---|---|
| A | 500 |
| B | 400 |
| C | 250 |
| D | 100 |
Table product_diff, is where I need to calculate, diff_a as another column where formula a-a, a-b, a-c, a-d carries over.
| product | avg_rev | diff_a |
|---|---|---|
| A | 500 | 0 |
| B | 400 | 100 |
| C | 250 | 250 |
| D | 100 | 400 |
My query so far:
select product, avg_rev, lag(avg_rev,1) over (order by product) as previous_value from product;
I can take difference between previous row minus current row by saying previous_value-avg_rev but what I need is for previous row to be constant, minus current row as carried over all the way.