2

我有 Microsoft SQL Server 2012,并且有一个表包含有关 BOM(物料清单)的所有信息。数据格式如下:

Item   | SubItem  | Quantity
item_1 | item_2   | 2
item_1 | item_3   | 3
item_1 | item_4   | 2
item_2 | item_5   | 2
item_2 | item_6   | 2

等等...

因此,如果我想要 10 件 item_1,那么它必须将所有项目和项目子项目的数量乘以这个乘数。我想通过查询来实现这种结果:

item_1 - 10pcs - 1 lvl
  item_2 - 20pcs - 2 lvl
    item_5 - 40pcs - 3 lvl
    item_6 - 40pcs - 3 lvl 
  item_3 - 30pcs - 2 lvl
  item_4 - 20pcs - 2 lvl

任何提示如何以一种好的方式实现这一点?如果这不可能与查询有关,那么我的另一个选择是在 Excel 的 VBA 中执行所有技巧。

4

1 回答 1

1

这可以通过递归查询来完成。这里有一些让你开始的东西:

with all_item_counts as (
select item, subitem, quantity as q, 0 as level from bom
union all 
select all_item_counts.item, bom.subitem, quantity * q, level + 1 
    from all_item_counts
    join bom on bom.item = all_item_counts.subitem
)
select item,subitem,sum(q) from all_item_counts
   group by item, subitem
   order by item, subitem

subItem查询的结果是每个需要的总数item

您可以在这里看到它在 SQLFiddle中工作。我在您的示例数据中添加了一些内容,以表明更复杂的案例有效。

于 2012-12-14T11:42:35.993 回答