简体   繁体   English

对于SQL Server 2005 Express中的循环?

[英]For Loop in SQL Server 2005 Express?

I have a program using SQL Server 2005 Express and I need some help looping through 2 tables to calculate inventory. 我有一个使用SQL Server 2005 Express的程序,我需要一些帮助循环通过2个表来计算库存。

  • Table 1 : stores all products with the inventory total upon setup Table 1 :在设置时存储具有库存总量的所有产品
  • Table 2 : stores the transactions against all products from table 1 Table 2 :存储针对表1中所有产品的交易

How can I loop through all items in table 2 and subtract that amount from table 1 counts? 如何遍历表2中的所有项目并从表1中减去该数量?

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 我需要从表1的每个事件中减去表1的总金额

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(*) . 如果每个条目都可能影响多个项目,那么您将使用sum(cnt) as cnt东西sum(cnt) as cnt而不是count(*)

Then, the query uses a left outer join . 然后,查询使用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. coalesce()用于处理日志表中没有匹配项的情况。 To avoid getting NULL , the NULL is turned into a 0 . 为避免获得NULLNULL变为0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM