考虑下表(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上出售,但在8.90的2011-3-25上再次购买,此后我们再也没有出售过它,所以它仍然在2011-03-26上的投资组合中-股票55在2011-03-21上购买,在2011-03-22上出售,所以不再在投资组合中-股票99在2011-03-21上购买,我们一直持有但从未出售,所以它仍然在2011-03-26上的投资组合中,价格为5.15 -股票1和<代码>D22都是在<代码>D23之前买卖的
因此,2011-03-26上的产品组合包括:
sp100_id buy_date buy_price
-------------------------------
11 2011-03-25 8.90
99 2011-03-21 5.15我的问题是:使用什么查询可以从表中返回上述输出?
SQLFiddle here
发布于 2012-08-31 18:29:05
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-31 18:44:19
这是一个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)https://stackoverflow.com/questions/12213379
复制相似问题