SQL subtract two rows based on date and another column

前端 未结 2 1980
梦如初夏
梦如初夏 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

    What I've done was I get two separate queries to get each stock's maximum date and minimum date. Try this,

    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 Demo

    UPDATE 1

    seeing your last sentence: Right now I just have two dates per company, but bonus upvotes if your query can handle any number of dates. What if you have records like this?

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

    what would be its result?

    enter image description here

提交回复
热议问题