【问题标题】:Selecting a price from a datelist based on an order date根据订单日期从日期列表中选择价格
【发布时间】: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


    【解决方案1】:

    您可以使用横向连接:

    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 子句中,如果您更喜欢该方法。

    【讨论】:

    • 谢谢 Gordon,我会试一试.. 从来没有想过将返回的字段排序和限制为一个...仍在学习中,非常感谢您的帮助。
    猜你喜欢
    • 2020-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-05
    • 2019-11-14
    • 2016-07-07
    • 2021-12-29
    • 1970-01-01
    相关资源
    最近更新 更多