A company sells Widgets that they store in several warehouses:. So I have these tables:
+----------+-------------+--------+------+
| WidgetID | Description | Price | .... |
+----------+-------------+--------+------+
| 1 | Red | 123.00 | |
| 2 | Blue | 321.00 | |
| 3 | .... | .... | |
| .... | | | |
+----------+-------------+--------+------+
and
+-------------+----------+------+
| WarehouseID | Location | .... |
+-------------+----------+------+
| 1 | Chicago | |
| 2 | Seattle | |
| 3 | .... | .... |
| .... | | |
+-------------+----------+------+
and
+-------------+----------+-------+
| WarehouseID | WidgetID | Count |
+-------------+----------+-------+
| 1 | 3 | 18 |
| 1 | 6 | 33 |
| 2 | 44 | 100 |
| 2 | 26 | 6 |
+-------------+----------+-------+
They sell Packages which contain various combinations of widgets, so I have this table which defines each package:
+-----------+----------+-------+
| PackageID | WidgetID | Count |
+-----------+----------+-------+
| 1 | 9 | 7 |
| 1 | 66 | 28 |
| 1 | 2 | 50 |
| 2 | 9 | 44 |
+-----------+----------+-------+
Now I know how to get how many of each type of widget they have:
SELECT
WidgetID, SUM([Count]) AS Available
FROM
WidgetLocations
GROUP BY
WidgetID;
and I have this query to get the widget requirements for each package:
SELECT
Packages.PackageID,
Packages.Description,
Packages.Cost,
PackageContents.WidgetID,
PackageContents.[Count] AS Required
FROM
Packages LEFT OUTER JOIN PackageContents ON Packages.PackageID = PackageContents.PackageID
What I can't figure out is how to combine these two queries to get the following result:
+-----------+----------+----------+-----------+
| PackageID | WidgetID | Required | Available |
+-----------+----------+----------+-----------+
It would be ideal if another query could show the Widget that limits the production of more of each package:
+-----------+------------+-------------------+-------------+
| PackageID | Production | Limiting WidgetID | Requirement |
+-----------+------------+-------------------+-------------+
where
- Production is the number of packages that can be made up from existing inventory
- Limiting widget is the one that has the smallest requirement of additional widgets to be able to make more packages
- Requirement is that quantity.
Unfortunately, that query is beyond my current SQL skills.