2016-06-28 65 views
2

我对SQL相当陌生,试图在特定的日期获得产品交易的价格,我在交易之前查找了该产品的最新价格在价格目录内。SQLiteStudio:从价格目录中获取最新价格

具体而言,我有以下两个表:

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 
          ) 

而得到以下输出:

ProductID | Price | Transaction_DT | Design 

1   | Null | 5/14/2016  | Plaid 
2   | 50 | 3/26/2016  | Solid 
3   | 22 | 4/12/2016  | PolkaDot 
4   | Null | 4/24/2016  | Solid 
5   | 15 | 2/24/2016  | PolkaDot 
6   | Null | 3/29/2016  | PinStripe 

我想将产品1,4和6的价格分别返回到10,8和17(除了相应的更改) ect价格是正确的输出),而不是我得到的空值。关于如何获得正确结果的任何想法?

+0

还有更多的价格..你想要最新的。年龄较大......? – scaisEdge

回答

1

您忘记了按照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 
          )