My current query SELECT * FROM foo ORDER BY date;
returns result:Currently I have data like this,
id | qty | unit_price | date | action
----------------------------------------------
1 | 2000 | 4.01235 | 2015-10-10 | in
2 | -30 | | 2015-10-11 | out
3 | 1800 | 4.9 | 2015-10-25 | in
4 | -1000 | | 2015-11-12 | out
5 | -980 | | 2015-11-20 | out
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');
unit_priceunit_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 row id=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 row id=1
for id=5
-> there's left only 970 with the first in action, but theres more with in action id=3
1800. So basically i could use -970
with price 4.01235
and -10
with price 4.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 to 5
decimals.
- 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 Basically it is FIFO calculation logic.