sql-server - 与子选择或子查询聚合
问题描述
我正在尝试进行一个查询,该查询根据来自不同仓库的组件单元总和的最低值返回我可以生产多少。
数据来自如下表:
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
我需要总结每个组件(泡罩、盒子、充电器......)总共有多少:BLISTER1:250 BOX1:400 CHARGER1:100
然后返回最小值除以 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);
解决方案
使用一些公用表表达式 (CTE) 来:
- 汇总仓库中的所有库存组件。
- 根据产品组成除以前面的总和。
这给出了:
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
用中间的 CTE 结果来查看它的实际效果。
推荐阅读
- reactjs - 状态已设置,但 firebase 未注册第一次点击
- jquery - JQuery on load 函数改变加载图像的 CSS 属性
- json - 如何阅读/解析 Firebase 响应 .createUserWithEmailAndPassword
- python - 如何运行多线程刮板
- sql-server - 在 SQL Server 中隐藏数据
- datastax - 如何使用用户定义的函数获取 cassandra 的 blob 列的大小?
- c# - DocuSign C# SDK 方法线程安全吗?
- react-native - react-native run-android 从终端失败
- powershell - 在 PowerShell 中获取字符串的权利
- c# - 如何使用 c# 应用程序登录到我的路由器