2016-04-02 35 views
0

我在我的數據庫中有5個表格,產品,purchase_orders,發票,invoice_details和product_prices及其模式如下所示。如何在銷售日期之前選擇最新購買價格?

Table: products 
id 
trade_name 

Table: purchase_orders 
id 
product_id 
created 

Table: invoices 
id 
created 

Table invoice_details 
id 
invoice_id 
product_id 
price_id 

Table product_prices 
id 
retail_price 
effective_from 
effective_to 

我認爲我需要以某種方式加入或檢查在purchase_orders上創建以在發票上創建。所以,我開始獲得藥物身份證,發票日期。

select d.id as drug_id 
     , i.created as invoice_created 
     , dp.retail_price 
from drugs d 
inner join invoice_details id 
     on d.id = id.drug_id 
inner join invoices i 
     on i.id = id.invoice_id 
inner join drug_prices dp 
     on dp.id = id.price_id 

下一步是匹配在發票上創建的,我必須在purchase_orders上創建,這是我沒有弄清楚的。

inner join (
      select  drug_id 
        , purchase_price 
        , ISNULL(created, CONVERT(DATETIME, '2015-10-07 01:37:12.370')) as created 
      from  purchase_orders po 
      ) as prepared_po 
      on prepared_po.created <= i.created 

我怎樣才能獲得我售出的每件商品的持續購買價格?

+0

爲什麼我會爲這個問題得到一個低估? –

+0

如果將一些示例數據和預期結果添加到查詢中可能會有所幫助。 – APH

回答

0

這裏有您需要的邏輯的簡化版本(我改名爲您的欄,它很容易看出這是哪個沒有做所有的中介聯接你已經寫自己):

;With CTE as (select a.productID, a.saledate, b.price, b.purchasedate 
    , row_number() over (partition by a.productID, a.saledate 
         order by b.purchasedate desc) RN 
from sales a 
left join purchases b 
on a.productID = b.productID and a.saledate >= b.purchasedate 
) 

Select productID, saledate, price, purchasedate 
from CTE where RN = 1 

基本上,您加入以獲取截至銷售日期的所有購買記錄,然後使用row_number查找最新的購買記錄。

http://sqlfiddle.com/#!6/a0f68/2/0

相關問題