我正在收集报价数据,并选择opt_ticker和quoteTimeStamp作为主键,以便可以随时间存储唯一的报价。现在,我想创建一个视图,在其中可以查看每个opt_ticker的最新报价(数据库中还有其他opt_tickers以及唯一的报价)。基本上想查看每种股票/期权的最新报价。
在上面的示例中,我想获取最后一行,因为它是该特定合同的最新时间戳。
我以为这个查询可以解决问题,但是mysql抱怨我需要分组。
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
这听起来很简单,但是我很难确定这一点,在此先感谢您。
答案 0 :(得分:2)
在MySQL 5.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
答案 1 :(得分:1)
只需四舍五入,这是使用联接执行此操作的一种规范方法:
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;