【发布时间】:2019-09-06 13:13:02
【问题描述】:
我有一张带有 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,这对于获取最新价格非常有用,但当您不需要最后一个价格时不是这样,而是在特定日期更早的价格。
我觉得这可能很容易,但我无法理解
我正在使用 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
【问题讨论】:
标签: sql postgresql subquery