Consider the following table (portfolio). It is a transaction log for a stock-market investor. Each day, he either buys, sells or holds (previously bought stocks which are not yet being sold) stocks (identified by sp100_id):
_date sp100_id action price
-----------------------------------
2011-03-21 11 buy 10.50
2011-03-21 55 buy 60.00
2011-03-21 99 buy 5.15
2011-03-22 11 sell 9.80
2011-03-22 55 sell 61.50
2011-03-22 99 hold 5.60
2011-03-23 1 buy 95.00
2011-03-23 2 buy 25.60
2011-03-23 99 hold
2011-03-24 1 sell 96.00
2011-03-24 2 hold
2011-03-24 99 hold
2011-03-25 11 buy 8.90
2011-03-25 2 sell 28.00
2011-03-25 99 hold
The log stops at 2011-03-25. For 2011-03-26, I want to know:
– what stocks are still left in the portfolio
– for what price and on what date these stocks were orginally bought
If we do this manually:
– stock 11 is bought on 2011-03-21, sold on 2011-03-22, but bought again on 2011-3-25 for 8.90 and we haven’t sold it since, so it is still in portfolio on 2011-03-26
– stock 55 is bought on 2011-03-21 and sold on 2011-03-22 so not in portfolio anymore
– stock 99 is bought on 2011-03-21 and we have held it and never sold so it is still in portfolio on 2011-03-26 for a price of 5.15
– stock 1 and 2 are both bought and sold before 2011-03-26
So the portfolio on 2011-03-26 consists of:
sp100_id buy_date buy_price
-------------------------------
11 2011-03-25 8.90
99 2011-03-21 5.15
My question is: with what query can the above output be returned from the table?
1 Answer