6

我需要使用前一个日期的最近日期减去 MySQL 中的两行:

起始表:

Stock       Date          Price
GOOG        2012-05-20    402
GOOG        2012-05-21    432
APPL        2012-05-20    553
APPL        2012-05-21    590
FB          2012-05-20     40
FB          2012-05-21     34

这是结果表:

Stock       Date          Price Change
GOOG        2012-05-21    30
APPL        2012-05-21    37
FB          2012-05-21    -6

现在我每家公司只有两个日期,但是如果您的查询可以处理任意数量的日期,则可以加分。

4

2 回答 2

4

我所做的是我得到两个单独的查询来获取每只股票的最大日期和最小日期。试试这个,

SELECT  maxList.stock, 
        maxList.Date,
        (maxlist.Price - minlist.Price) totalPrice
FROM
    (
        SELECT  a.*
        FROM    tableName a INNER JOIN
        (
            SELECT      Stock, MAX(date) maxDate
            FROM        tableName
            GROUP BY    Stock
        ) b ON  a.stock = b.stock AND
                a.date = b.maxDate
    ) maxList INNER JOIN
    (
        SELECT  a.*
        FROM    tableName a INNER JOIN
        (
            SELECT      Stock, MIN(date) minDate
            FROM        tableName
            GROUP BY    Stock
        ) b ON  a.stock = b.stock AND
                a.date = b.minDate
    ) minList ON maxList.stock = minList.stock

SQLFiddle 演示

更新 1

看到你的最后一句话:Right now I just have two dates per company, but bonus upvotes if your query can handle any number of dates.如果你有这样的记录怎么办?

FB          2012-05-20     40
FB          2012-05-21     34
FB          2012-05-22     42

结果会是什么?

在此处输入图像描述

于 2012-09-07T00:44:27.023 回答
1

我知道这已经被回答了,但是这个问题引起了我的兴趣,所以我想我会试一试。

我假设您可能想查看任意两个连续日期之间的差异。

所以对于以下数据:

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 已经多年了,所以我忘记了差异)。

于 2012-09-07T15:10:16.233 回答