I have two tables with the following (simplified) structures:
-
table "Factors" which holds data about purchased goods’ factors and has these columns:
FactorSerial, PurchaseDate, PurchasedGood
-
table "Prices" which holds goods prices on different dates
Serial, GoodCode, EvaluationDate, Price
A price is valid until a new row with the same Code but different date is added and thus updates its value
Now, I want to create a table which adds the price to the table 1 according to purchase date.
So if we have:
PurchaseDate PurchasedGood
-----------------------------
05/20/2011 A111
and:
GoodCode EvaluationDate Price
--------------------------------
A111 02/01/2011 100
...
A111 04/01/2011 110
...
A111 06/01/2011 120
the result would be
PurchaseDate PurchasedGood Price
-----------------------------------
05/20/2011 A111 110
Preferred method is creating the view Prices1 as
Serial GoodCode StartDate EndDate Price
and then joining Factors with this view by
PurchasedDate between StartDate AND EndDate
Can anybody show me how to create view1 (or obtaining the final result with any other method)? Thanks in advance!
P.S. sorry for my bad English!
Here is a query that returns such data. The syntax is pretty standard SQL, I believe, but this was tested on SQL Server (looks like you may be using PostgreSQL with your "serial" naming).
This query assumes that there are no Purchases before a Price existed.
Also, considering:
betweenis inclusive. Using this method that you’ve described, you would get duplicates if aPurchaseDatelies on theEndDateof one row and theStartDateof another.