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
我怎樣才能獲得我售出的每件商品的持續購買價格?
爲什麼我會爲這個問題得到一個低估? –
如果將一些示例數據和預期結果添加到查詢中可能會有所幫助。 – APH