Pregunta

I have a program using SQL Server 2005 Express and I need some help looping through 2 tables to calculate inventory.

  • Table 1: stores all products with the inventory total upon setup
  • Table 2: stores the transactions against all products from table 1

How can I loop through all items in table 2 and subtract that amount from table 1 counts?

If I have my query like this then I get data for each product

SELECT 
     ii.ItemNum, ii.ItemName, ii.OzOnHand
FROM 
     dbo.InventoryItems ii
INNER JOIN 
     dbo.InventoryLog il ON ii.ItemNum = il.InvItemNum
WHERE 
     ii.active = 1

I need each occurrence from table 2 to be subtracted from table 1's total amount

¿Fue útil?

Solución

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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top