As long as there is no overlap between your product compositions (so no two products share a common component, otherwise you are looking at something way more complex), then the query below should give you a solution.
Sample data
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);
Solution
Using some common table expressions (CTE's) to:
- Sum up all the inventory components across the warehouses.
- Divide the previous sums according to the product composition.
This gives:
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;
Result
codartp producibleAmount
------- ----------------
REF1 50
REF2 150
Fiddle to see it in action with intermediate CTE results.