这个查询困扰了我好几天..我有2张桌子
A
Itemnum ¦ Binnum ¦ Quantity
-----------------------------
A ¦ 1 ¦ 25
A ¦ 2 ¦ 25
B ¦ 1 ¦ 25
C ¦ 1 ¦ 15
B
Itemnum ¦ Unit cost
---------------------
A ¦ 0.05
A ¦ 0.06
B ¦ 0.10
C ¦ 0.15
C ¦ 0.15
我想要做的是获得以下结果:
itemnum ¦ quantity ¦ Unit cost
------------------------------------
A ¦ 50 ¦ 0.55
B ¦ 25 ¦ 0.10
C ¦ 15 ¦ 0.15
所以我想得到表A中每个项目编号的总数量以及表B中每个项目的平均成本。我构建的查询还有其他事情正在进行,但它正在做的是将每个数量相加时间它在表B中有一条线 - 所以它对于A来说是100。
到目前为止,这是我的查询..感谢您的帮助!感谢
select invbalances.itemnum, sum(invbalances.curbal) as curbal,
inventory.costtype, item.commodity, item.commoditygroup,
inventory.siteid,
inventory.location, inventory.itemsetid, item.description as itemDesc,
inventory.issueunit as iUnit, avg(ifc.unitcost) LIFOFIFOCOST, invc.stdcost
INVUNITCOST
from invbalances
join inventory on invbalances.itemnum = inventory.itemnum and
invbalances.siteid = inventory.siteid
join item on invbalances.itemnum = item.itemnum and item.itemsetid =
invbalances.itemsetid
left outer join invlifofifocost ifc on invbalances.itemnum =
ifc.itemnum and inventory.costtype in ('LIFO','FIFO')
left outer join invcost invc on invbalances.itemnum = invc.itemnum and
inventory.costtype = 'STANDARD'
where invbalances.itemnum NOT IN (select matusetrans.itemnum from
matusetrans where matusetrans.itemnum is not null group by itemnum)
and invbalances.itemnum NOT IN (select matrectrans.itemnum from
matrectrans where matrectrans.itemnum is not null group by itemnum)
group by invbalances.itemnum, inventory.costtype, item.commodity,
item.commoditygroup, inventory.siteid, inventory.location,
inventory.itemsetid,
item.description, inventory.issueunit, ifc.unitcost, invc.stdcost
答案 0 :(得分:2)
您希望单独进行聚合,然后将结果连接在一起:
select i.itemnum, i.quantity, ib.vgUnitCost
from (select itemnum, sum(quantity) as quantity
from inventory i
group by itemnum
) i join
(select itemnum, avg(UnitCost) as avgUnitCost
from invbalances ib
group by itemnum
) ib
on i.itemnum = ib.itemnum;
如果一个或另一个表中缺少某些项目,则外部联接可能更合适。
这回答了你的问题,它指定了两个表。我不知道查询中其余表格的用途。