This is an example of a join to an aggregated table (I think that is the best way to understand it):
SELECT ii.ItemNum, ii.ItemName, ii.OzOnHand, ii.OzOnHand - coalesce(il.cnt, 0)
FROM dbo.InventoryItems ii LEFT JOIN
(select il.InvItemNum, sum(OzRemoved) as cnt
from dbo.InventoryLog il
group by il.InvItemNum
) il
ON ii.ItemNum = il.InvItemNum
WHERE ii.active = 1;
The subquery groups everything in the log and counts the number of entries. If each entry could affect more than one item, then you would use something like sum(cnt) as cnt
instead of count(*)
.
Then, the query uses a left outer join
. This type of join ensures that all inventory items remain, even those with nothing in the log. Finally, the count is subtracted from what is available in set up. The coalesce()
is to handle the situation where there are no matches in the log table. To avoid getting NULL
, the NULL
is turned into a 0
.