如何在销售日期之前选择最新的购买价格?

时间:2016-04-02 03:37:05

标签: sql sql-server

我的数据库中有5个表,产品,purchase_orders,invoice,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上创建以在发票上创建。所以,我开始获得药物ID,发票日期。

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

如何获得我销售的每件商品的持续购买价格?

1 个答案:

答案 0 :(得分: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