Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
983 views
in Technique[技术] by (71.8m points)

mysql - SQL subtract two rows based on date and another column

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

Starting table:

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

This is the result table:

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

Right now I just have two dates per company, but bonus upvotes if your query can handle any number of dates.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...