Here is my Database design. I plan on calculating the quantity of components in a view by subtracting the Order_LineQuantity
from the Component_UsedQuantity.
The problem I am having is surely elementary, but my current view doesn't work because it is summing all the Order_LineQuantities
from all Components and likewise with the Component_UsedQuantities
instead of giving the proper difference/quantity for each individual component.
Create View Inventory3(ComponentID, quantity) AS
SELECT
DISTINCT(ComponentID) AS ComponentID,
SUM(Order_LineQuantity) - SUM(Component_UsedQuantity) AS quantity
FROM
Component
INNER JOIN
Order_Line ON Order_LineComponentID = ComponentID
INNER JOIN
Component_Used ON Component_UsedComponentID = ComponentID
How can I get the proper quantity for each individually different componentID?
If you just use SUM()
function it will sum all the values of the table. If you want to sum only the related values, you have to first group the values by an id
and then sum them. That's what the below sub query does.
Here is a model of Table1- Order_Line
Here is a model of Table2- Component_Used
I have filled only necessary details. You can see that there are multiple values of Order_LineQuantity
for a given component.
And similarly multiple values exist for Component_UsedQuantity
for a given component.
I have linked this using the ComponentID
from Component Table.
SELECT ComponentID AS ComponentID,(ordertable.sumorder-componenttable.sumcomponent) as quantity
FROM Component,
(SELECT Order_LineComponentID as id,SUM(Order_LineQuantity) as sumorder FROM Order_Line GROUP BY Order_LineComponentID)ordertable,
(SELECT Component_UsedComponentID as id,SUM(Component_UsedQuantity) as sumcomponent FROM Component_Used GROUP BY Component_UsedComponentID)componenttable
WHERE
ComponentID=ordertable.id and ComponentID=componenttable.id
Now when you execute the query, it selects the required details after all the grouping operations.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.