我知道这已经被回答了,但是这个问题引起了我的兴趣,所以我想我会试一试。
我假设您可能想查看任意两个连续日期之间的差异。
所以对于以下数据:
GOOG 2012-09-07 42.34
GOOG 2012-09-06 44.56
GOOG 2012-09-01 44.32
FB 2012-09-07 17.82
FB 2012-08-05 12.98
你会得到:
GOOG 2012-09-07 2012-09-06 -2.22
GOOG 2012-09-06 2012-09-01 0.24
FB 2012-09-07 2012-08-05 4.84
我为此写的查询是:
SELECT t1.Stock, t1.Date AS CurrentDate, oldDate.Date AS OldDate, (t1.Price - oldDate.Price) AS PriceChange
FROM MP_StockTable t1
JOIN (SELECT t2.Stock, t2.Date AS date1, (SELECT MAX(t3.Date) FROM MP_StockTable t3 WHERE t3.Date < t2.Date AND t3.Stock = t2.Stock GROUP BY t3.Stock) AS date2
FROM MP_StockTable t2) AS StockDates ON StockDates.Stock = t1.Stock AND StockDates.date1 = t1.Date
JOIN MP_StockTable oldDate ON oldDate.Stock = t1.Stock AND oldDate.Date = StockDates.date2
内联表基本上计算每行最接近的先前日期。所以对于上面的数据,生成的表是这样的:
GOOG 2012-09-07 2012-09-06
GOOG 2012-09-06 2012-09-01
GOOG 2012-09-01 NULL
FB 2012-09-07 2012-08-05
FB 2012-08-05 NULL
然后我们使用该表中的两个日期来获得我们的两个价格点。
注意:我在 SQLServer 中进行测试,如果这需要对 mySql 进行一些调整,我深表歉意(使用 mySql 已经多年了,所以我忘记了差异)。