根据订单日期从日期列表中选择价格

时间:2019-09-06 13:13:02

标签: sql postgresql subquery

我有一个包含Costprices的表和一个包含订单行的表

CostPrices表:

Price_id, product_id, date, price
1,24,2018-08-06,100
2,24,2019-01-01,80
3,56,2018-11-11,500
4,57,2018-07-10,400
5,58,2017-01-01,500

订单表:

order_id, product_id, date, customer_id, qty, sales_price
1, 24, 2018-08-10, 344, 10, 250
2, 24, 2018-11-11, 538, 5, 250
3, 24, 2019-06-06, 678, 100, 250

我需要在订单行日期选择有效的成本价。喜欢:

select
    ol.order_id,
    ol.product_id,
    ol.date,
    ol.customer_id,
    ol.qty,
    ----costprice @ orderdate ---,
    ol.sales_price

from orderlines as ol

left outer join Costprices as cp on cp.product_id = ol.product_id

我一直在研究如何执行此操作,通常使用计算出的maxdate,这对于获取最新价格非常有用,但是当您不需要最后一个价格时,而不是在某个特定日期更早的价格时,< / p>

我觉得这可能很容易,但是却束手无策

我正在使用Postgres SQL 10尝试在tableplus中编写sql查询

select
ol.order_id,
ol.product_id,
ol.date`
ol.customer_id,
ol.qty,
----costprice @ orderdate ---,
ol.sales_price

from orderlines as ol

let outer join Costprices as cp on cp.product_id = ol.product_id

我期待

order_id, product_id, date, customer_id, qty, Costprice ,sales_price
1, 24, 2018-08-10, 344, 10, 100, 250
2, 24, 2018-11-11, 538, 5, 100, 250
3, 24, 2019-06-06, 678, 100, 80, 250

1 个答案:

答案 0 :(得分:0)

您可以使用横向连接:

select ol.*, cp.costprice
from orderlines ol left join lateral
     (select cp.*
      from costprices cp
      where cp.product_id = ol.product_id and
            cp.date <= ol.date
      order by cp.date desc
      limit 1
     ) cp
     on 1=1;

根据您的情况,您还可以使用相关子查询。基本上,如果愿意,可以将cp移到select子句中。

相关问题