【问题标题】:How to read from database which stocks have been bought but not yet sold?如何从数据库中读取哪些股票已买入但尚未卖出?
【发布时间】:2012-08-31 18:45:53
【问题描述】:

考虑下表 (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,我想知道: - 投资组合中还剩下哪些股票 - 最初购买这些股票的价格和日期

如果我们手动执行此操作: - 股票112011-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 - 股票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 here

【问题讨论】:

    标签: mysql sql


    【解决方案1】:
    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
    

    【讨论】:

    • 这确实很干净 :-) 谢谢!
    【解决方案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)
    

    【讨论】:

      猜你喜欢
      • 2017-09-26
      • 1970-01-01
      • 2021-11-29
      • 2021-06-07
      • 2011-03-15
      • 2019-06-06
      • 1970-01-01
      • 1970-01-01
      • 2010-12-12
      相关资源
      最近更新 更多