使用子选择或子查询聚合

Aggregate with subselect or subquery

我正在尝试查询 return我可以根据来自不同仓库的组件单元总和的最低值生产多少。

数据来自如下表格:

e.table
-------
codartp    codartc      unicompo
REF1       BLISTER1       1
REF1       BOX1           1
REF1       CHARGER1       2
REF2       BLISTER2       1
REF2       BOX2           1

s.table
------
codart      unidades      codalm
BLISTER1      100           4 
BLISTER1      150           1
BOX1          100           1
BOX1          100           4
BOX1          200           2
CHARGER1      50            3
CHARGER1      50            4 
BLISTER2      500           1
BLISTER2      300           4 
BOX2          150           2

我需要计算每个组件(泡罩、盒子、充电器...)总共有多少: 水泡1:250 BOX1:400 充电器 1:100

然后return 最低值除以 unicompo(我需要的组件数)。以我的零件库存,我只能生产 50 个单位的 REF1:100/2

这是我的子选择:

(select min(val) from (select sum(s1.unidades/e.unicompo) as val 
    from __STOCKALMART s1
    left join escandallo e on e.codartc = s1.codart
    where s1.codalm not in (0,9999) and e.codartp = l.codart) t) as PRODUCIBLE

预期的结果是这样的:

l.codart  producible
REF1          50
REF2          150

但我只设法调用了 min(在某些仓库中为 0)或组件的总和,而不是总和之后的 min。我不知道我是否在解释自己。问我是否需要澄清什么

感谢您的帮助

只要您的产品组成之间没有重叠(因此没有两个产品共享一个共同的组件,否则您正在寻找更复杂的东西),那么下面的查询应该会给您一个解决方案。

示例数据

create table ProductComponent
(
  codartp nvarchar(4),  -- product
  codartc nvarchar(10), -- component
  unicompo int          -- amount
);

insert into ProductComponent (codartp, codartc, unicompo) values
('REF1', 'BLISTER1', 1),
('REF1', 'BOX1'    , 1),
('REF1', 'CHARGER1', 2),
('REF2', 'BLISTER2', 1),
('REF2', 'BOX2'    , 1);

create table ComponentInventory
(
  codart nvarchar(10), -- component
  unidades int,        -- amount
  codalm int           -- warehouse
);

insert into ComponentInventory (codart, unidades, codalm) values
('BLISTER1', 100, 4), 
('BLISTER1', 150, 1),
('BOX1'    , 100, 1),
('BOX1'    , 100, 4),
('BOX1'    , 200, 2),
('CHARGER1', 50 , 3),
('CHARGER1', 50 , 4), 
('BLISTER2', 500, 1),
('BLISTER2', 300, 4), 
('BOX2'    , 150, 2);

解决方案

使用一些常见的 table 表达式 (CTE) 来:

  1. 汇总仓库中的所有库存组件。
  2. 根据产品成分划分前面的金额。

这给出:

with cti as -- component inventory total
(
  select ci.codart,
         sum(ci.unidades) as unidades
  from ComponentInventory ci
  group by ci.codart
),
pci as -- product component inventory
(
  select pc.codartp,
         cti.unidades / pc.unicompo as maxPart
  from ProductComponent pc
  join cti
    on cti.codart = pc.codartc
)
select pci.codartp,
       min(pci.maxPart) as producibleAmount
from pci
group by pci.codartp
order by pci.codartp;

结果

codartp producibleAmount
------- ----------------
REF1    50
REF2    150

Fiddle 看看它与中间 CTE 结果的关系。