sql - 根据订单日期从日期列表中选择价格
问题描述
我有一张带有 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
解决方案
您可以使用横向连接:
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
子句。
推荐阅读
- firebase - 如何使用 Firebase 云消息传递上的用户属性评估目标用户
- excel - VBA/Excel - 将工作表复制到另一个工作簿(替换现有值)
- javascript - 无法在 Ajax outputString 中插入换行符
- encoding - 为什么 mips 中的 sw 指令使用字节作为偏移单位?
- swift - 在 swift xcode 项目中未读取协议
- kubernetes - kubectl list / 删除所有已完成的作业
- ruby - 当我使用 RegEx 类时,此 RegEx 不起作用
- python - 我们可以将 .txt 文件导入 python 吗?
- session - Veracode CWE ID 259
- supercollider - Supercollider 3.9 中无法理解错误消息“addr”