如何按日期从PostgreSQL中的查询显示表中的值

  

我有2张桌子。我需要的order_product_table和selling_product_table   加入两个表并使用日期获取值(如果您看到最终表)   会明白我想要的。谁知道该怎么做??

order_product_table

id    | date         | Product_id  | value 
-------------------------------------------
1     | 2017-07-01   | 1           | 10 
3     | 2017-10-02   | 2           | 30
4     | 2018-01-20   | 1           | 20
5     | 2018-02-20   | 2           | 40

selling_product_table

id    | date         | Product_id  | seling_price
------------------------------------------------
1     | 2017-08-01   | 1           | 500
2     | 2017-10-06   | 2           | 100
3     | 2017-12-12   | 1           | 500
4     | 2018-06-25   | 2           | 100
5     | 2018-07-20   | 1           | 500

最终结果

id    | date         | Product_id  | value | selling_price
---------------------------------------------------------
1     | 2017-08-01   | 1           | 10    |  500
2     | 2017-10-06   | 2           | 30    |  100
3     | 2017-12-12   | 1           | 10    |  500
4     | 2018-06-25   | 2           | 40    |  100
5     | 2018-07-20   | 1           | 20    |  500
okletsgo 回答:如何按日期从PostgreSQL中的查询显示表中的值

select s.date,s.product_id,(select o.value from order_product_table o
where o.date < s.date) as value,s.seling_price 
from selling_product_table s 
left join order_product_table o on  s.product_id=o.product_id 
  

尝试类似这样的方法。会得到结果。

,

Select * from selling_product_table s left join order_product_table o on (product_id,date)这是假设所有售出的产品均已订购。

,

作为相关子查询的正确解决方案是:

select s.date,(select o.value
        from order_product_table o
        where o.product_id = s.product_id and
              o.date <= s.date
       ) as value,s.selling_price 
from selling_product_table s ;

注意:

  • 不需要显式JOIN
  • ORDER BY在子查询中非常重要。
  • 相关子句需要在产品上匹配。

但是,我将其称为横向连接:

select s.date,o.value,s.selling_price 
from selling_product_table s left join lateral
     (select o.*
      from order_product_table o
      where o.product_id = s.product_id and
            o.date <= s.date
      order by o.date desc
      limit 1
     ) o;
本文链接:https://www.f2er.com/3168401.html

大家都在问