I'm trying to create a query that returns all the prices from table skucompetition
for 开发者_开发技巧every date in table creationdateformat
.
To clarify, creationdateformat has these dates in it:
creationdateformat
2010-10-25
2010-10-26
2010-11-10
2010-11-24
2010-11-25
skucompetition has these prices for it:
sku creationdate price
PCR-BR2495112 2010-10-26 16:06:03 24.99
PCR-BR2495112 2010-11-10 13:01:43 27.99
PCR-BR2495112 2010-11-25 12:24:26 26.51
For date 2010-10-25 it should return 0, as it was before the first price existed.
For date 2010-10-26 it should return 24,99
For date 2010-11-10 and 2010-11-24 it should return 27.99
For date 2010-11-25 it should return 26.51
And so on.
How can this best be achieved?
This should point you in the right direction...
Judging from your sample data, you're looking for the most recent record either before or on a specific date.
You're only interested in a single record, so you should limit your selection to the first record.
You can simplify the before or on part. Anything 'before or on today' is the same as anything 'before tomorrow'. So you'll be looking for anything 'before the input date plus one day'. This simplifies the query, because you won't have to worry about the exact time of day.
Finally, to make sure you get the most recent record, you'll have to order the records.
In pseudo-code it would be:
select the first record
from skucompetition
where creationdate is before (input date + one day)
order by creationdate so most recent record comes first
You should handle the special case of returning 0 in your application. If you have constructed the query correctly, it won't match any records for input dates before the first date. That's when your application should handle the 'return 0' case.
I would create a query that:
- selects all records with the creationdate on or later than the date you're looking at
- order those from the earliest to the latest
- and then use a "limit" to only return the first record
The exact syntax will of course depend on which RDBMS you use
SELECT price FROM skucompetition
WHERE sku = "<sku>" AND DATE(creationdate) <= "<date>"
ORDER BY date DESC LIMIT 1
This will select the first record with the right SKU that is not older than "date". If there's none, NULL will be returned.
精彩评论