SQL subtract two rows based on date and another column

前端 未结 2 2010
梦如初夏
梦如初夏 2020-12-09 06:48

I need to subtract two rows in MySQL by using the most recent date from the previous date:

Starting table:

Stock       Date          Price
GOOG              


        
2条回答
  •  情书的邮戳
    2020-12-09 07:38

    I know this was answered already, but the problem caught my interest so I thought I'd give it a try.

    I assumed you might want to see the difference between any two consecutive dates.

    So for the following data:

    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
    

    You would get:

    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
    

    The query I wrote for this is:

    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 
    

    The inline table basically calculates the closest previous date for each row. So for the data above, the generated table would like this:

    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
    

    We then use the two dates from that table to get our two price points.

    NOTE: I was testing in SQLServer, so apologies if this needs some tweaks for mySql (it's been years since used mySql, so I've forgotten the differences).

提交回复
热议问题