I try to update my base SellAll with the value of a previous stock. I have this request so far :
UPDATE SellAll
set S_stock = (S_in - S_out) + monthn1.stock
FROM
(
SELECT
LAG(S_stock,1,0) OVER (ORDER BY S_famille,S_year, S_month) AS stock,
S_id
FROM SellAll
) AS monthn1
WHERE SellAll.S_id = monthn1.S_id;
But i don t have the result wanted.
For example i have this grid
id | year | month | famille | stock | in | out |
---|---|---|---|---|---|---|
573 | 2023 | 9 | 2 | -6 | 20 | 18 |
574 | 2023 | 10 | 2 | 1 | 18 | 21 |
575 | 2023 | 11 | 2 | -7 | 21 | 20 |
576 | 2023 | 12 | 2 | 2 | 25 | 20 |
With my request i have this
id | year | month | famille | stock | in | out |
---|---|---|---|---|---|---|
573 | 2023 | 9 | 2 | -6 | 20 | 18 |
574 | 2023 | 10 | 2 | 0 | 18 | 21 |
575 | 2023 | 11 | 2 | 2 | 21 | 20 |
576 | 2023 | 12 | 2 | -2 | 25 | 20 |
But i want this :
id | year | month | famille | stock | in | out |
---|---|---|---|---|---|---|
573 | 2023 | 9 | 2 | -6 | 20 | 18 |
574 | 2023 | 10 | 2 | -3 | 18 | 21 |
575 | 2023 | 11 | 2 | -2 | 21 | 20 |
576 | 2023 | 12 | 2 | 3 | 25 | 20 |
I want to subtract (in – out) + stock of previous row
Can you help me ?
I want to subtract (in – out) + stock of previous row in PostgreSQL
2
Answers
Thanks for your answer !
I m more close of the good result with this request :
UPDATE SellAll set S_stock = monthn1.stock FROM
( SELECT (S_in - S_out)+LAG(S_stock,1,0) OVER (ORDER BY S_famille,S_year, S_month) AS stock, S_id FROM SellAll ) AS monthn1 WHERE SellAll.S_id = monthn1.S_id and monthn1.stock<>0;
But still not but may be there is something that i dont understand because the result seems good at the moment of the update but i want the good stock of the previous row after the update and it seems not the case.
For example I have this grid :
With my request i have this result
But i want
first CHECK is the value of stock is correct
it seems not correct, but
this should look better:
TEST it:
output:
P.S. These are not the value you want, but the seem correct to /me…. 😉
see: DBFIDDLE