我正在为股票数据库撰写查询,我正在寻找每年(2010年至2016年)价格上涨的前五大股票。现在我写的是这样的:
(
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
并重复每年直到2016年。
create table语句是:
CREATE TABLE Stocks (
Year DATE
Ticker VARCHAR(8),
High FLOAT,
Low FLOAT,
Volume FLOAT,
PRIMARY KEY(Ticker, Year)
);
结果数据集将是这样的:
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)
有没有更好更简洁的方法来写这个?
答案 0 :(得分:-1)
你可以试试IN语句。
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
希望这有帮助。