Question : SQL 2005

i have a information in 4 tables.
1) inventory master - each item can have multiple rows because of different warehouse ,for eg.
itemid                 physical available        warehouseid
1000                   10                           Main
1000                   12                           Old

inventory master is joined to billofmaterial usuing itemid

2)order master - for eg.
order no                     ord qty
123456                       10
256465                        5
3)billofmaterialtransactions table - item no 1000 can appear multiple times for diferent orders
itemid                used for                  req/unit                
1000                   123456                       5            (i.e 5 x 10)
takes order qty from order master (link - 123456)

4)executed - itemno can appear multiple time for different orders / or with same order nos
itemid                 used for                executed qty
1000                   123456                  2                 (i.e 2*5)
1000                   123456                  1                 (i.e 1*5)

itemid is used for joining to other tables

i need to take a minus stock report

item id         onhand            onorder                allocated                    freestock
1000            22                    0                           50- 15=35                 -13

can someone help me on this?

regards
                           

Answer : SQL 2005

Probably another way to do this, but I have to run out of the office for a bit; however, wanted to share what should work for you.  Basically use derived tables to aggregate values so that you are always joining one for one OR in cases where there may not be any results you use left join and coalesce()/isnull().  

If for example, you may not have any records in inventory master for an item that is on order, you may need a full outer join but assuming that you always have an inventory location defined even if it is at 0 qty.

select i.itemid, i.boh as onhand
, 0 as onorder -- add join to your PO/WO table to get this value
, coalesce(b.allocated, 0) as allocated
, i.boh - coalesce(b.allocated, 0) as freestock
from (
  select itemid, sum(physicalavailable) as boh
  from inventorymaster
  group by itemid
) i
left outer join (
  select b.itemid, sum((o.orderqty - coalesce(e.executedqty, 0))* b.req_unit) as allocated
  from billofmaterialstransactions b
  inner join ordermaster o on o.orderno = b.usedfor
  left outer join (
     select itemid, usedfor, sum(executedqty) as executedqty
     from executed
      group by itemid, usedfor
  ) e on e.itemid = b.itemid and e.usedfor = b.usedfor
  group by b.itemid
) b on b.itemid = i.itemid

;

If you need further explanation, I will most certainly offer it when I return so just post any questions you have on what I am doing.
Random Solutions  
 
programming4us programming4us