如何从数据库中读取已购买但尚未售出的股票?

时间:2012-08-31 10:19:17

标签: mysql sql

考虑下表(portfolio)。它是股票市场投资者的交易日志。每天,他buysellhold s(之前购买的尚未售出的股票)股票(由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

日志在2011-03-25处停止。对于2011-03-26,我想知道:   - 投资组合中仍有哪些股票   - 以什么价格以及这些股票在什么日期被购买

如果我们手动执行此操作:   - 库存11是在2011-03-21上购买的,已在2011-03-22上销售,但在2011-3-25上再次购买8.90,我们从未将其出售,因此它仍然在2011-03-26的投资组合中   - 股票552011-03-21上购买并在2011-03-22上出售,因此不再在投资组合中出售   - 股票99是在2011-03-21上购买的,我们已经持有并且从未出售,因此它仍然在2011-03-26的投资组合中,价格为5.15   - 1

之前买卖的股票22011-03-26

因此2011-03-26上的投资组合包括:

sp100_id  buy_date    buy_price
-------------------------------
11        2011-03-25  8.90
99        2011-03-21  5.15

我的问题是:用什么查询可以从表中返回上面的输出?

SQLFiddle here

2 个答案:

答案 0 :(得分:2)

select t1.sp100_id, t1._date as buy_date, t1.price
from (select * from portfolio where action='buy')  t1
    left join (select * from portfolio where action='sell') t2 
      on t1.sp100_id=t2.sp100_id
    and t1._date<t2._date
where t2.sp100_id is null

答案 1 :(得分:2)

这是sqlfiddle demo

select t0.* from portfolio t0
join
(
select sp100_id,max(_date) mdate from portfolio t
   where action = 'buy'
      and 
        not exists (select sp100_id from portfolio t2
                     where t2.sp100_id=t.sp100_id
                           and t2._date>t._date
                           and t2.action='sell')
group by sp100_id
) t1 on (t0.sp100_id=t1.sp100_id) and (t0._date=t1.mdate)