Need to find the sequential difference and average between within a columns of two rows group by brand column and order by bill_id column and find the difference of worth column between rows in a single query.
I have a data
brand bill_id worth
Moto 1 2550
Samsung 1 3430
Samsung 2 3450
Moto 2 2500
Moto 3 2530
Expected Output
brand bill_id worth net_diff avg_diff
Moto 1 2550 0 00
Moto 2 2560 10 5
Moto 3 2540 -20 -5
Samsung 1 3430 0 0
Samsung 2 3450 20 10
2
Answers
With the following data :
One possible solution could be :
But I do not understand the computation formulae of your example for AVG…
It appears that by average you are looking for 1/2 the difference between 2 consecutive
bill_id
for abrand
. You can get this by applying the lag() function twice (with answer from @SQLpro as a base) arriving at: (see demo)NOTE: Due to inconsistency between Input and Results it does not exactly produce you expected results.