我有两个表:
价格
股票行情关闭
AAPL 3/20/2019 $ 100
AAPL 3/21/2019 $ 101.5
AAPL 3/22/2019 $ 106.5
GOOG 2019/3/20 $ 100
GOOG 2019/3/21 $ 130
GOOG 2019/3/22 $ 110
MSFT 3/20/2019 $ 184.5
MSFT 3/21/2019 $ 188.5
MSFT 3/22/2019 $ 210
IBM 3/20/2019 $ 72
IBM 3/21/2019 $ 70
IBM 3/22/2019 $ 10
股票
股票交易所
AAPL纳斯达克
高仪纳斯达克
MSFT纳斯达克
IBM NYSE
我想返回收盘价涨幅最大的'NYSE'股票代码从2019-03-20到2019 03-21。我有:
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;
但是它返回'ERROR 1064(42000):您的SQL语法有错误;请查看与您的MySQL服务器版本相对应的手册以获取正确的语法,以在“ SELECT D1.ticker,MAX(D1.close-D2.close)FROM PRICE D1,PRICE D2,STOCK S WHERE'第1行”附近使用>
IBM应该作为输出返回,因为它是NYSE中唯一的股票行情。
我是SQL的新手,任何建议将不胜感激:)
答案 0 :(得分:0)
使用自联接:
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;
如果需要交换,则只需要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;