简体   繁体   English

MYSQL查询返回两天之间价格涨幅最高的值

[英]MYSQL query to return the value with the highest price increase between two days

I have two tables: 我有两张桌子:

PRICE 价钱
ticker date close 股票日期关闭
AAPL 3/20/2019 $100 AAPL 3/20/2019 100美元
AAPL 3/21/2019 $101.5 AAPL 3/21/2019 $ 101.5
AAPL 3/22/2019 $106.5 AAPL 3/22/2019 $ 106.5
GOOG 3/20/2019 $100 GOOG 3/20/2019 100美元
GOOG 3/21/2019 $130 GOOG 3/21/2019 130美元
GOOG 3/22/2019 $110 GOOG 3/22/2019 110美元
MSFT 3/20/2019 $184.5 MSFT 3/20/2019 $ 184.5
MSFT 3/21/2019 $188.5 MSFT 3/21/2019 $ 188.5
MSFT 3/22/2019 $210 MSFT 3/22/2019 210美元
IBM 3/20/2019 $72 IBM 3/20/2019 $ 72
IBM 3/21/2019 $70 IBM 3/21/2019 70美元
IBM 3/22/2019 $10 IBM 3/22/2019 10美元

STOCK 股票
ticker exchange 股票交易所
AAPL NASDAQ AAPL纳斯达克
GOOG NASDAQ GOOG纳斯达克
MSFT NASDAQ MSFT纳斯达克
IBM NYSE IBM纽约证券交易所

and I want to return the ticker that is in 'NYSE' with the highest increase in closing price from 2019-03-20 to 2019 03-21. 我想要回到“纽约证券交易所”的股票代码,收盘价从2019-03-20到2019 03-21最高涨幅。 I have: 我有:

SELECT DISTINCT T.ticker 
FROM PRICE T 
WHERE T.ticker IN SELECT D1.ticker, MAX(D1.close-D2.close) 
                  FROM PRICE D1, PRICE D2, STOCK S 
                  WHERE S.exchange='NYSE' AND D1.date = '2019-03-21' AND D2.date = '2019-03-20' AND D1.ticker = D2.ticker GROUP BY D1.ticker) 
GROUP BY T.ticker;

But it returns 'ERROR 1064 (42000): You have an error in your SQL syntax; 但是它返回'ERROR 1064(42000):你的SQL语法有错误; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT D1.ticker, MAX(D1.close-D2.close) FROM PRICE D1, PRICE D2, STOCK S WHERE ' at line 1' 检查与MySQL服务器版本对应的手册,以便在'SELECT D1.ticker,MAX(D1.close-D2.close)从PRICE D1,PRICE D2,STOCK S'在第1行'附近使用正确的语法

IBM should return as output, as it is the only ticker in NYSE. IBM应该作为输出返回,因为它是纽约证券交易所唯一的股票代码。

I'm completely new to SQL and any suggestions would be appreciated :) 我是SQL的新手,任何建议都会受到赞赏:)

Use a self-join: 使用自联接:

select p1.ticket
from price p1 join
     price p2
     on p1.ticker = p2.ticker and
        p1.date = '2019-03-20' and
        p2.date = '2019-03-21'
order by p2.price - p1.price desc
limit 1;

You only need the join to stock if you need the exchange (which your query suggests you want, but the explanation doesn't mention): 如果您需要交换(您的查询建议您需要,但解释未提及),您只需要join stock

select p1.ticket
from price p1 join
     price p2
     on p1.ticker = p2.ticker and
        p1.date = '2019-03-20' and
        p2.date = '2019-03-21' join
     stock s
     on p1.ticker = s.ticker
where s.exchange = 'NYSE'
order by p2.price - p1.price desc
limit 1;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM