我有两个表,我需要使用 Select 加入它们,但我遇到了问题。 这些表看起来像这样: 表价格
Product_ID | Buy_date | Buy_price |
1 | 16.10.01 | 2.50 |
1 | 16.11.02 | 3.20 |
2 | 16.10.31 | 3.80 |
表过期日期
Product_ID | Count | Exp_date |
1 | 1000 | 17.10.01|
1 | 500 | 17.11.31|
2 | 500 | 17.11.01|
我需要在 Oracle PL/SQL 中编写一个选择,它给出以下结果:
Product_ID| Count | Exp_date| last_buy_price|
1 | 1000 | 17.10.01| 3.20 |
1 | 500 | 17.31.31| 3.20 |
2 | 500 | 17.11.01| 3.80 |
这意味着它将为我提供每个到期日期以及表expire_date中的产品计数,并将其与table_price中带有product_id的上次购买价格相匹配(始终与上次购买价格,按buy_date列排序) 请大家帮助我,我尝试了很多代码,但仍然无法得到满意的结果
最佳答案
使用 keep
的相关子查询可能是性能最好的方法:
select ed.*,
(select max(p.buy_price) keep (dense_rank first order by p.buy_date desc)
from table_price p
where p.product_id = ed.product_id
) as last_buy_price
from expire_date ed;
当然,您也可以在 from
子句中表达这一点:
select ed.*, p.last_buy_price
from expire_date ed left join
(select p.product_id,
max(p.buy_price) keep (dense_rank first order by p.buy_date desc) as last_buy_price
from table_price p
) p
on p.product_id = ed.product_id;
关于sql - 选择连接两个表 Oracle PL/SQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41017723/