【问题标题】:Getting latest quote data for stock获取股票的最新报价数据
【发布时间】:2020-10-02 22:32:33
【问题描述】:

我正在收集报价数据并选择 opt_ticker 和 quoteTimeStamp 作为主键,以便我可以随时间存储唯一的报价。我现在想创建一个视图,我可以在其中看到每个 opt_ticker 的最新报价(数据库还有其他带有唯一报价的 opt_ticker)。基本上想查看每只股票/期权的最新报价。

在上面的示例中,我想获取最后一行,因为它是该特定合约的最新时间戳。

我认为这个查询可以解决问题,但 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

这听起来很容易,但我很难弄清楚这一点,提前谢谢你。

【问题讨论】:

    标签: mysql sql innodb groupwise-maximum


    【解决方案1】:

    在 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
    

    【讨论】:

    • 错误代码:1064。您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以在第 4 行的 '(partition by opt_ticker order by quoteTimeStamp desc) as rn from optionquo​​tes' 附近使用正确的语法得到上述错误
    • @nGX 是的,刚刚注意到你有 MySQL 5.x。请使用第一个查询。
    • 就像一个穿着闪亮盔甲的骑士。您已经解决了过去几天我一直在努力解决的问题。谢谢你。为什么sql复杂/s
    【解决方案2】:

    为了完善答案,以下是使用连接的规范方法:

    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;
    

    【讨论】:

      猜你喜欢
      • 2011-03-15
      • 1970-01-01
      • 2018-02-16
      • 1970-01-01
      • 2014-06-19
      • 1970-01-01
      • 2016-11-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多