获取股票最新报价数据

bttbmeg0  于 2021-08-09  发布在  Java
关注(0)|答案(2)|浏览(300)

我正在收集报价数据,并选择opt\u ticker和quotetimestamp作为主键,以便随着时间的推移存储唯一的报价。我现在想创建一个视图,在其中可以看到每个opt\u ticker的最新报价(数据库中也有其他opt\u ticker的唯一报价)。基本上希望看到每个股票/期权的最新报价。

在上面的例子中,我想得到最后一行,因为它是特定合同的最新时间戳。
我原以为这个查询可以解决这个问题,但mysql抱怨说我需要执行group-by。

select symbol,opt_ticker,ask,bid,exp,strike,type,max(quoteTimeStamp)
from optionquotes
group by opt_ticker

21:36:42    select symbol,opt_ticker,ask,bid,exp,strike,type,max(quoteTimeStamp) from optionquotes group by opt_ticker,symbol LIMIT 0, 1000 Error Code: 1055. Expression #3 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'od2.optionquotes.ask' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by  0.000 sec

这里是我的服务器信息,如果它有帮助

Server 
Product: (Ubuntu) 
Version: 5.7.30-0ubuntu0.16.04.1 
Connector 
Version: C++ 8.0.20

这听起来很容易,但我有最艰难的时间来解决这个问题,提前谢谢你。

mxg2im7a

mxg2im7a1#

在MySQL5.x中,您可以执行以下操作:

select *
from optionquotes
where (opt_ticker, quoteTimeStamp) in (
  select opt_ticker, max(quoteTimeStamp)
  from optionquotes
  group by opt_ticker
)

在mysql 8.x中,您可以执行以下操作:

select *
from (
  select *,
    row_number() over(partition by opt_ticker order by quoteTimeStamp desc) as rn
  from optionquotes
) x
where rn = 1
dgiusagp

dgiusagp2#

为了给出完整的答案,这里有一个使用连接的标准方法:

SELECT oq1.*
FROM optionquotes
INNER JOIN
(
    SELECT opt_ticker, MAX(quoteTimeStamp) AS maxQuoteTimeStamp
    FROM optionquotes
    GROUP BY opt_ticker
) oq2
    ON oq1.opt_ticker = oq2.opt_ticker AND
       oq1.quoteTimeStamp = oq2.maxQuoteTimeStamp;

相关问题