3

考虑下表 ( portfolio)。它是股票市场投资者的交易日志。每天,他要么buys、sells 或holds(之前购买的股票尚未出售)股票(由 标识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-258.90从那以后我们没有卖出它,所以它仍然在投资组合中2011-03-26 - 股票55在买入2011-03-21和卖出,2011-03-22所以不再在投资组合中 -股票99是买入的2011-03-21,我们一直持有,从未卖出,所以它仍然在投资组合中2011-03-26,价格为5.15 - 股票12之前买入和卖出2011-03-26

所以投资组合2011-03-26包括:

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

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

SQLFiddle在这里

4

2 回答 2

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
于 2012-08-31T10:29:04.557 回答
2

这是一个sqlfiddle 演示

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)
于 2012-08-31T10:44:19.043 回答