sql - calculating Product Cost Price in runtime -



sql - calculating Product Cost Price in runtime -

i developing inventory system, using average cost method, average cost cost of product changes on each new purchase. database using sql server 2008

now need calculate cost of goods sold in report, have add together cost cost each sale of product, cost cost should relevant 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 create sale report, sale-1 should take 5.5, sale-2, 6.5 , sale-3 should pick 7.5 product cost price. , if cannot find purchase should pick opening cost_price product_table.

i looking such query should job???

i think may can done grouping , inner joins, cannot figured out.

any suggestions please ????

regards raza

i'm not big fan of correlated subqueries in select clause. part of reason aesthetic , mmaintainability. prefer have table references in 1 place, in from clause. part of reason performance; tend think turn nested loop joins (usually worse). admittedly, sql optimizers have gotten much improve in lastly few years.

but 1 case think best approach:

[trouble uploading]

the correlated subquery . . .

select s.*,

           (select top 1 ave_cost_price purchase p             p.purchase_date <= sys.sale_date , p.product_id = s.product_id             order p.purchase_date desc            ) purchaseprice sales s

and performance should fine if have index on purchase(product_id, purchase_date) or purchase(product_id, purchase_date, ave_cost_price).

sql sql-server-2008

Comments

Popular posts from this blog

javascript - mongodb won't find my schema method in nested container -

Hibernate criteria by a list of natural ids -

ios - Lagging ScrollView with UIWebview inside -