Pregunta

this query has been bothering me for a few days.. I have 2 tables

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

What I want to do is get the following results:

 itemnum  ¦  quantity  ¦  Unit cost
------------------------------------
    A     ¦     50     ¦    0.55
    B     ¦     25     ¦    0.10
    C     ¦     15     ¦    0.15

So I want to get the total quantity for each item number in table A and the average cost for each item from table B. The query I've built has other things going on but what it is doing is summing the quantity every time it has a line in table B - so it would be 100 for A.

Here is my query so far.. appreciate your help! Thanks

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
¿Fue útil?

Solución

You want to do the aggregations separately and then join the results together:

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;

If some items are missing from one or the other table, then an outer join might be more appropriate.

This answers your question, which specifies two tables. I do not know what the rest of the tables in your query are for.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top