2016-06-28 5 views
2

Ich bin ziemlich neu in SQL und versuche, den Preis für eine Produkttransaktion an einem bestimmten Datum zu erhalten, meine Suche nach dem letzten Preis dieses Produkts vor der Transaktion in einem Preiskatalog.SQLiteStudio: Erhalte den neuesten Preis aus einem Preiskatalog

Insbesondere habe ich die beiden folgenden Tabellen:

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 

ich den folgenden Code eingegeben haben:

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 
          ) 

Und erhalten die folgende Ausgabe:

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 

Ich möchte um den Preis für Produkte 1, 4 und 6 auf 10, 8 und 17 zurückzugeben (zusätzlich zu den korr ect-Preise, die richtig ausgegeben wurden) anstelle der Null-Werte, die ich bekomme. Irgendwelche Ideen, wie ich die richtigen Ergebnisse erzielen kann?

+0

gibt es mehr als einen Preis .. Sie wollen die neueste.? die älteren ... ? – scaisEdge

Antwort

1

Sie haben vergessen, die korrelierte Abfrage nach ProduktID zu filtern. Sie erhalten nicht das korrekte aktuelle Datum für das Produkt. Sie müssen diese Abfrage verwenden:

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 
          ) 
Verwandte Themen