情况:我正在处理的Access数据库将零件分成左右两部分。两侧可以使用相同的部件。我正在尝试创建一个查询来计算每件所需的单个零件总数。
问题:如何创建允许UNION多个字段的查询,如下所示?
示例:
Table 1:
Part # |Left Part | Left Part Qty | Right Part | Right Part Quantity
1 xyz 5 xyz 7
2 abc 8 lmn 4
Table 2:
Part # | Needed
1 10
2 25
Query:
Part | Quantity
xyz 120 ((5 + 7) * 10)
abc 200 (8 * 25)
lmn 100 (4 * 25)
编辑:我很抱歉,但我忘了添加一部分内容。我没有意识到我需要从另一个表中乘以一个因子。
答案 0 :(得分:0)
如果您有所有部件的表格,那么您可以这样做:
select p.part, nz(l.cnt, 0) + nz(r.cnt, 0)
from (parts as p left join
(select leftpart, count(*) as cnt
from table t
group by leftpart
) as l
on p.part = l.leftpart
) left join
(select rightpart, count(*) as cnt
from table
group by rightpart
) as r
on p.part = r.rightpart;
如果您没有这样的表,可以从查询创建视图:
select leftpart
from table
union
select rightpart
from table;
然后使用表格中的视图。
答案 1 :(得分:0)
您可以这样做:
Select
BothParts, Sum(BothQty) As TotalQuantity
From
(Select
[Left Part] As BothParts, [Left Part Qty] As BothQty
From
YourTable
Union All
Select
[Right Part] As BothParts, [Right Part Qty] As BothQty
From
YourTable) As T
Group By BothParts;