SQLiteStudio:从价格目录获取最新价格
我对SQL相当陌生,正在尝试获取特定日期的产品交易价格,我在价格目录中查找交易之前该产品的最新价格 具体而言,我有以下两个表格:SQLiteStudio:从价格目录获取最新价格,sql,sqlite,date,price,Sql,Sqlite,Date,Price,我对SQL相当陌生,正在尝试获取特定日期的产品交易价格,我在价格目录中查找交易之前该产品的最新价格 具体而言,我有以下两个表格: Transactions Catalog ---------------------------------------------------------------------------- ProductID | Design | Transaction_DT ProductID |
Transactions Catalog
----------------------------------------------------------------------------
ProductID | Design | Transaction_DT ProductID | Price | Effective_DT
1 | Plaid | 5/14/2016 1 | 20 | 4/22/2016
2 | Solid | 3/26/2016 1 | 10 | 5/2/2016
3 | PolkaDot | 4/12/2016 1 | 5 | 5/15/2016
4 | Solid | 4/24/2016 2 | 50 | 3/22/2016
5 | PolkaDot | 2/24/2016 2 | 25 | 4/1/2016
6 | PinStripe | 3/29/2016 2 | 10 | 4/2/2016
3 | 30 | 4/5/2016
3 | 25 | 4/9/2016
3 | 22 | 4/12/2016
4 | 12 | 3/15/2016
4 | 8 | 3/27/2016
4 | 6 | 4/25/2016
5 | 15 | 2/23/2016
5 | 11 | 2/25/2016
5 | 6 | 2/28/2016
6 | 26 | 2/2/2016
6 | 17 | 3/19/2016
6 | 13 | 5/16/2016
我已输入以下代码:
SELECT Transactions.ProductID,
Catalog.Price,
Transactions.Transaction_DT,
Transactions.Design
FROM Transactions
LEFT JOIN
Catalog ON Transactions.ProductID = Catalog.ProductID AND
Catalog.Effective_DT = (
SELECT MAX(Effective_DT)
FROM Catalog
WHERE Effective_DT <= Transactions.Transactions DT
)
我想返回产品1、4和6的价格分别为10、8和17,除了正确输出的正确价格,而不是我得到的空值。有没有关于如何获得正确结果的想法?您忘记了按productID筛选相关查询。您没有获得产品的正确最新日期。您需要使用此查询:
SELECT Transactions.ProductID,
Catalog.Price,
Transactions.Transaction_DT,
Transactions.Design
FROM Transactions
LEFT JOIN
Catalog ON Transactions.ProductID = Catalog.ProductID AND
Catalog.Effective_DT = (
SELECT MAX(Effective_DT)
FROM Catalog
WHERE Effective_DT <= Transactions.Transactions_DT
and ProductID = Transactions.ProductID
)
这不仅仅是一个价格。。你想要最新的吗。?老的?
SELECT Transactions.ProductID,
Catalog.Price,
Transactions.Transaction_DT,
Transactions.Design
FROM Transactions
LEFT JOIN
Catalog ON Transactions.ProductID = Catalog.ProductID AND
Catalog.Effective_DT = (
SELECT MAX(Effective_DT)
FROM Catalog
WHERE Effective_DT <= Transactions.Transactions_DT
and ProductID = Transactions.ProductID
)