-1

我正在尝试找出在 Postgres 中表示 BoM 的最佳模式结构。假设一个零件可以有多个相同的子零件,我可以添加一个数量列,但这些零件也可能有多个子零件。

如果我想知道每个部分的总使用量,postgres 是否可以在分层查询中使用数量列?

BOM 表示物料清单。

4

1 回答 1

2

据我了解您的问题,是的,您可以在使用分层 BOM 时包含数量。我理解您的问题的方式是,如果一个 BOM 条目的数量为 10,则其子项的数量需要乘以 10(因为您有 10 倍于该“子”项)。

用下表和样本数据:

create table bom_entry
(
  entry_id integer primary key,
  product text, -- should be a foreign key to the product table
  amount integer not null,
  parent_id integer references bom_entry
);

insert into bom_entry
values 
(1, 'Box', 1, null),
(2, 'Screw', 10, 1),
(3, 'Nut', 2, 2),
(4, 'Shim', 2, 2),
(5, 'Lock', 2, 1),
(6, 'Key', 2, 5);

所以我们的盒子需要 10 个螺丝,每个螺丝需要 2 个螺母和 2 个垫片,所以我们总共需要 20 个螺母和 20 个垫片。我们也有两把锁,每把锁有两把钥匙,所以我们一共有 4 把钥匙。

您可以使用递归 CTE 遍历树并计算每个项目的数量。

with recursive bom as (
  select *, amount as amt, 1 as level
  from bom_entry
  where parent_id is null
  union all 
  select c.*, p.amt * c.amount as amt, p.level + 1
  from bom_entry c
    join bom p on c.parent_id = p.entry_id
)
select rpad(' ', (level - 1)*2, ' ')||product as product, amount as entry_amount, amt as total_amount
from bom
order by entry_id;

rpad/level 用于缩进以可视化层次结构。上面的查询返回以下内容:

product  | entry_amount | total_amount
---------+--------------+-------------
Box      |            1 |            1
  Screw  |           10 |           10
    Nut  |            2 |           20
    Shim |            2 |           20
  Lock   |            2 |            2
    Key  |            2 |            4
于 2019-02-22T21:36:44.273 回答