Currently I have data like this,
CREATE TABLE foo (id, qty, unit_price, date, action) AS
VALUES
(1, 2000, 4.01235, '2015-10-10'::timestamp, 'in'),
(2, -30, NULL , '2015-10-11'::timestamp, 'out'),
(3, 1800, 4.9 , '2015-10-25'::timestamp, 'in'),
(4, -1000, NULL , '2015-11-12'::timestamp, 'out'),
(5, -980, NULL , '2015-11-20'::timestamp, 'out');
I need to get calculated avg price for outgoing rows so that result look like this.
id | qty | unit_price | date | action ---------------------------------------------- 1 | 2000 | 4.01235 | 2015-10-10 | in 2 | -30 | 4.01235 | 2015-10-11 | out 3 | 1800 | 4.9 | 2015-10-25 | in 4 | -1000 | 4.01235 | 2015-11-12 | out 5 | -980 | 4.02141 | 2015-11-20 | out
unit_price
is calculated for outgoing in this way:
- for
id=2
, since there's 2000 unused from only one income the result unit_price is the same as first income rowid=1
- for
id=4
, there's still 1970 unused and it's bigger than needed (-1000) - so result unit_price is still the same as first income rowid=1
- for
id=5
, there's left only 970 with the first in action, but theres more with in actionid=3
1800. So basically i could use-970
with price4.01235
and-10
with price4.9
. So as result i get the avg price for this row like this((-970*4.01235)+(-10*4.9)) / -980 = 4.02141
when rounding to5
decimals.
All the price calculations have to consider date
column. Basically it is FIFO calculation logic.
Does anyone have idea how to do this kind of calculation?
date
. I know that i should separate somehow in and out actions and then do calculations. I'll to write attempt that i have already.