Case:
I select an initial date and an end date, it should bring me the movements of all the products in that date range, but if there were movements before the initial date (records in table), I want to obtain the previous sum (prevData)
If the first move is exit 5 and the second move is income 2.
I would have in the first row (prevData-5), second row would have (prevData-5 + 2) and thus have a cumulative.
The prevData would be calculated as the sum of the above, validating the product id of the record, I made the query but if the product has 10 movements, I would do the query 10 times, and how would I identify the sum of another product_id?
SELECT
ik.id,
ik.quantity,
ik.date,
ik.product_id,
#balance = (SELECT SUM(quantity) FROM table_kardex WHERE product_id = ik.product_id AND id < ik.id)
from table_kardex ik
where ik.date between '2021-11-01' and '2021-11-15'
order by ik.product_id,ik.id asc
I hope you have given me to understand, I will be attentive to any questions.
table_kardex
id | quantity | date | product_id |
---|---|---|---|
1 | 8 | 2020-10-12 | 2 |
2 | 15 | 2020-10-12 | 1 |
3 | 5 | 2021-11-01 | 1 |
4 | 10 | 2021-11-01 | 2 |
5 | -2 | 2021-11-02 | 1 |
6 | -4 | 2021-11-02 | 2 |
is the total sum(quantity) that is less than the id of that record obviously with the same product_id, for the example the id 1 and 2 would be the prev data
result
id|quantity|date|product_id|balance
3 5 2021-11-01 1 20 (15+5)
5 -2 2021-11-02 1 18 (15+5-2)
4 10 2021-11-01 2 18 (8+10)
6 -4 2021-11-02 2 14 (18-4)
It can be done with a normal query, or using a view or cursors, maybe you could guide me, I have changed to MySQL 8.