简体   繁体   中英

Subtract current row from previous row, keeping previous row value as constant — SQL

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 aa, ab, ac, ad 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.

You need the difference of avg_rev of the 1st product with the current row's avg_rev :

SELECT product, 
       avg_rev, 
       FIRST_VALUE(avg_rev) OVER (ORDER BY product) - avg_rev AS diff_a 
FROM product;

See the demo .
Results:

product avg_rev diff_a
A 500 0
B 400 100
C 250 250
D 100 400

If you specifically want one of the products, I would use conditional logic:

select product, avg_rev,
       avg_rev - max(case when product = 'A' then avg_rev end) over () as diff_a
from product;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM