Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/64.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 如何从数据库中读取哪些股票已经买入但尚未卖出?_Mysql_Sql - Fatal编程技术网

Mysql 如何从数据库中读取哪些股票已经买入但尚未卖出?

Mysql 如何从数据库中读取哪些股票已经买入但尚未卖出?,mysql,sql,Mysql,Sql,考虑下表。它是股票市场投资者的交易日志。每天,他购买、出售或持有以前购买的股票,但这些股票尚未出售,由sp100_id标识: 日志在2011年3月25日停止。2011-03-26,我想知道: -投资组合中还有哪些股票 -这些股票最初是以什么价格和日期购买的 如果我们手动执行此操作: -股票11于2011年3月21日买入,于2011年3月22日卖出,但于2011年3月25日以8.90的价格再次买入,此后我们再也没有卖出过,因此在2011年3月26日仍在投资组合中 -股票55在2011年3月21日购

考虑下表。它是股票市场投资者的交易日志。每天,他购买、出售或持有以前购买的股票,但这些股票尚未出售,由sp100_id标识:

日志在2011年3月25日停止。2011-03-26,我想知道: -投资组合中还有哪些股票 -这些股票最初是以什么价格和日期购买的

如果我们手动执行此操作: -股票11于2011年3月21日买入,于2011年3月22日卖出,但于2011年3月25日以8.90的价格再次买入,此后我们再也没有卖出过,因此在2011年3月26日仍在投资组合中 -股票55在2011年3月21日购买,在2011年3月22日出售,因此不再在投资组合中 -99号股票于2011年3月21日购买,我们持有该股票,从未出售,因此该股票仍在2011年3月26日的投资组合中,价格为5.15 -股票1和股票2在2011年3月26日之前买卖

因此,2011年3月26日的投资组合包括:

sp100_id  buy_date    buy_price
-------------------------------
11        2011-03-25  8.90
99        2011-03-21  5.15
我的问题是:通过什么查询可以从表中返回上述输出

这是一个


这的确很干净:-谢谢!
sp100_id  buy_date    buy_price
-------------------------------
11        2011-03-25  8.90
99        2011-03-21  5.15
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
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)