我似乎正在努力获得每一行连续2天的股票价格之间的平均差异,并且会对此有所帮助。我相信使用内部联接可能有一种更简单的方法,但我真的很挣扎。
这是我的表
Symbol Date Price Date Price Date Price 1250 2015-01-14 47.51 2015-01-13 48.30 2015-01-12 48.80
我正在尝试计算所有行的最近两天价格之间的平均百分比差异。我的表目前只有符号,日期和价格的数据,我想要的是
Symbol Date Price % Change Date Price % Change Date Price 1250 2015-01-14 47.51 -1.63 2015-01-13 48.30 2.02 2015-01-12 48.80
感谢您提供任何帮助或指导!
答案 0 :(得分:0)
试试这个:
SELECT
subQuery1.Symbol,
subQuery1.Date AS 'Date 1',
subQuery1.Price AS 'Price 1',
ROUND(((subQuery1.Price - subQuery2.Price) / subQuery2.Price) * 100, 2) AS '% Change',
subQuery2.Date AS 'Date 2',
subQuery2.Price AS 'Price 2',
ROUND(((subQuery2.Price - subQuery3.Price) / subQuery3.Price) * 100, 2) AS '% Change',
subQuery3.Date AS 'Date 3',
subQuery3.Price AS 'Price 3'
FROM
(SELECT Symbol, Date, Price FROM tbl) AS subQuery1,
(SELECT Symbol, Date, Price FROM tbl) AS subQuery2,
(SELECT Symbol, Date, Price FROM tbl) AS subQuery3
WHERE
subQuery1.Symbol = subQuery2.Symbol
AND subQuery2.Symbol = subQuery3.Symbol
AND subQuery1.Date = subQuery2.Date + INTERVAL 1 DAY
AND subQuery2.Date = subQuery3.Date + INTERVAL 1 DAY
对于大型数据集,性能不会很好,因为它涉及三个子查询,临时表和没有索引......