I have 2 tables : Production and Delivery, each having ID INT, Product_ID INT, Date DATE, Quantity INT. Product_ID is a foreign key linking to the Product table.
For each table, I am able to have a total by month, by product like so (eg for table Delivery, the same being for table Production) :
Code: Select all
SELECT DATE_FORMAT(Delivery.Date, '%m-%Y') AS DATE, Product_ID, SUM(Delivery.Quantity) AS Quantity_OUT FROM Delivery WHERE Delivery.Date >= NOW() GROUP BY YEAR(Delivery.Date), MONTH(Delivery.Date), Product_ID ORDER BY Delivery.Date ASC;
+---------+------------+--------------+
| DATE | Product_ID | Quantity_OUT |
+---------+------------+--------------+
| 03-2016 | 1 | 100 |
| 03-2016 | 2 | 200 |
| 03-2016 | 9 | 1000 |
| 04-2016 | 1 | 500 |
| 04-2016 | 2 | 100 |
| 04-2016 | 9 | 2000 |
and I do the same with table Production, with SUM(Production.Quantity) AS Quantity_IN.
I would like to join those 2 tables and have (Quantity_IN - Quantity_OUT) AS Stock, where for each Product_ID Stock is an accumulated value (should I base this on another subquery?) to return something like this:
+-----------+---------------+-----------------+--------------------+---------+
| DATE | Product_ID | Quantity_IN | Quantity_OUT | Stock |
+-----------+---------------+-----------------+--------------------+---------+
| 03-2016 | 1 | 100 | 100 | 0 |
| 03-2016 | 2 | 100 | 200 | -100 |--------- |
| 03-2016 | 9 | 1000 | 500 | 500 |..........| Stock from 03-2016 is accumulated into 04-2016
| 04-2016 | 1 | 500 | 200 | 300 |...........|
| 04-2016 | 2 | 100 | 100 | -100 | <------- |
| 04-2016 | 9 | 2000 | 2000 | 500 |
For Product_ID 2:
+-----------+---------------+-----------------+--------------------+---------+
| DATE | Product_ID | Quantity_IN | Quantity_OUT | Stock |
+-----------+---------------+-----------------+--------------------+---------+
| 03-2016 | 2 | 100 | 200 | -100 |
| 04-2016 | 2 | 100 | 100 | -100 |
Stock for 04-2016 is -100, because it is Stock value of 03-2016 (-100) + Stock value of 04-2016 (0).
This table would then allow me to graph each Product_ID to get a visual idea of the future estimated inventory. But I don't know how to get this done. I need help on how to join those 2 tables properly and how to accumulate the Stock for each Product_ID. Any suggestions?
Thanks