[英]Left Join on MAX(DATE)
I have 2 tables: Transactions (a) and Prices (b). 我有2张表:交易(a)和价格(b)。 I want to retrieve the price from table b that is valid on the transaction date.
我想从表b检索在交易日期有效的价格。
Table a contains a history of article transactions: Store_type, Date, Article, ... 表a包含商品交易记录:Store_type,Date,Article,...
Table b contains a history of article prices: Store_type, Date, Article, price 表b包含商品价格的历史记录:Store_type,Date,商品,价格
Currently i have this: 目前我有这个:
Select
a.Store_type,
a.Date
a.Article,
(select b.price
from PRICES b
where b.Store_type = a.Store_type
and b.Article = a.Article
and b.Date = (select max(c.date)
from PRICES c
where c.Store_type = a.Store_type
and c.Article = a.Article
and c.date <= a.date)) AS ART_PRICE
from TRANSACTIONS a
It works just fine but it seems to take very long because of the double subquery. 它工作得很好,但由于要使用double子查询,因此似乎要花费很长时间。 Can the same be done with a LEFT JOIN?
可以通过LEFT JOIN进行同样的操作吗?
Can try using the below query ? 可以尝试使用以下查询吗?
SELECT a.Store_type, a.Date, a.Article, b.Price
FROM TRANSACTIONS a
LEFT JOIN PRICES b ON a.Store_type = b.Store_type
AND a.Article = b.Article
AND b.Date = (SELECT MAX (c.Date)
FROM PRICES c
WHERE a.Store_type = c.Store_Type
AND a.Article = c.Article
AND c.Date <= a.Date)
It still has one subquery though, used to retrieve the maximum date. 但是,它仍然具有一个子查询,用于检索最大日期。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.