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
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?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…