Possible Duplicate:
SQL Query to get latest price
I have a database containing stock price history. I want to select most recent prices for every stock that is listed. I know PostreSQL has a DISTINCT ON statement that would suit ideally here.
Table columns are name
, closingPrice
and date
; name
and date
together form a unique index.
The easiest (and very uneffective) way is
SELECT * FROM stockPrices s
WHERE s.date =
(SELECT MAX(date) FROM stockPrices si WHERE si.name = s.name);
Much better approach I found is
SELECT *
FROM stockPrices s JOIN (
SELECT name, MAX(date) AS date
FROM stockPrices si
GROUP BY name
) lastEntry ON s.name = lastEntry.name AND s.date = lastEntry.date;
What would be an efficient way to do this? What indexes should I create?
duplicate of:
SQL Query to get latest price