I am developing an Inventory system, using average cost method, where average cost price of product changes on each new purchase. Database I am using is SQL Server 2008
Now I need to calculate COST OF GOODS SOLD in a report, where I have to Add Cost Price for Each Sale of a product, but this COST PRICE should be relevant to a that specific Purchase period.
My Purchase Table
Purchase_Date Product_ID Ave_Cost_Price
1-jan-2013 1 5.5
15-jan-2013 1 6.5
30-jan-2013 1 7.5
My Sales Table
Sale_Date Product_ID Sale_Price Cost_Price
5-jan-2013 1 10 ? SALE-1
17-jan-2013 1 10 ? SALE-1
31-jan-2013 1 15 ? SALE-1
Now when I create a SALE report, SALE-1 should take 5.5, SALE-2, 6.5 and SALE-3 should pick 7.5 as Product cost price. and if it cannot find any purchase then it should pick opening Cost_Price from product_table.
I am looking for Such a Query which should do the job???
I think may be it can be done by some grouping and inner joins, but cannot figured it out.
any suggestions please ????
regards Raza
I’m not a big fan of correlated subqueries in the
selectclause. Part of the reason is aesthetic and mmaintainability. I prefer to have all table references in one place, in thefromclause. Part of the reason is performance; I tend to think that they turn into nested loop joins (usually for worse). Admittedly, SQL optimizers have gotten much better in the last few years.But this is one case where I think it is the best approach:
[trouble uploading]
The correlated subquery is . . .
(select top 1 ave_cost_price
from purchase p
where p.purchase_date <= sys.sale_date and p.product_id = s.product_id
order by p.purchase_date desc
) a purchaseprice
from sales s
And the performance should be fine if you have an index on
purchase(product_id, purchase_date)or evenpurchase(product_id, purchase_date, ave_cost_price).