情况:我正在处理的Access数据库将零件分成左右两部分。两侧可以使用相同的部件。我正在尝试创建一个查询来计算每周所需的单个部件的总数。
问题:如何创建允许UNION多个字段和JOIN的查询,如下所示?
Table 1:
Part # |Left Part | Left Part Qty | Right Part | Right Part Quantity
1 xyz 5 lmn 7
2 abc 8 xyz 4
Table 2:
Part # | Needed
1 10
2 25
Query:
Part | Quantity
xyz 150 (5 * 10) + (4 * 25)
abc 200 (8 * 25)
lmn 70 (7 * 10)
答案 0 :(得分:1)
您在MS Access中遇到问题,因为您无法将union
/ union all
放入子查询中。如果你有一个零件表(你应该有),那么你可以使用left join
,所以我认为以下是你想要的:
select p.partname,
sum(nz(t1l.leftpartqty * t2.needed) + nz(t1r.rightpartqty * t2.needed))
from ((part as p inner join
table2 as t2
on p.part# - t2.part#
) left join
table1 as t1l
on t1l.leftpart = p.partname
) left join
table1 as t1r
on t1r.rightpart = p.partname
group by p.partname;
如果您没有这样的表格,可以使用视图执行union all
并从那里开始。
答案 1 :(得分:1)
这也应该有效:
SELECT T.Part, SUM(T.Qty * S.Needed) AS Quantity
FROM (
SELECT A.[Part#] AS PartNo, A.LeftPart As Part, A.LeftPartQty As Qty
FROM Table1 AS A
UNION ALL
SELECT B.[Part#] AS PartNo, B.RightPart As Part, B.RightPartQty As Qty
FROM Table1 AS B
) AS T INNER JOIN Table2 AS S ON T.PartNo = S.[Part#]
GROUP BY T.Part
ORDER BY T.Part
结果:
Part Quantity
abx 200
lmn 70
xyz 150
有关详细信息,请参阅:
UNION (MS Access)
Subqueries (MS Access)
INNER JOIN Operations (MS Access)
LEFT JOIN, RIGHT JOIN Operations (MS Access)