I am writing a query for a stock database and I am looking for the top 5 stocks in terms of price increase for each year (2010 - 2016). Right now I am writing it like this:
(
SELECT Ticker, Year, MAX(High - Low)
FROM Stocks
WHERE Year = 2010
GROUP BY Ticker
ORDER BY MAX(High - Low) DESC
LIMIT 5
)
UNION ALL
(
SELECT Ticker, Year, MAX(High - Low)
FROM Stocks
WHERE Year = 2011
GROUP BY Ticker
ORDER BY MAX(High - Low) DESC
LIMIT 5
)
UNION ALL
and repeating that for each year until 2016.
The create table statement is:
CREATE TABLE Stocks (
Year DATE
Ticker VARCHAR(8),
High FLOAT,
Low FLOAT,
Volume FLOAT,
PRIMARY KEY(Ticker, Year)
);
And the resulting data set would be something like this:
Year Ticker MAX(High - Low)
---------------------------------
2010 GOOG 100
2010 FB 99
2010 AAPL 98
2010 NFLX 97
2010 ABCD 96
2011 FB 120
2011 ABCD 112
etc... (Top 5 in terms of high-low per year)
Is there a better and more concise way to write this?
You can try IN statement.
SELECT Ticker, Year, MAX(High - Low)
FROM Stocks
WHERE Year IN ('2010', '2011', '2012', '2013', '2014', '2015', '2016')
GROUP BY Ticker
ORDER BY MAX(High - Low) DESC
Hope this helps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.