Sql: 如何获取前一天的收盘报价?

问题描述 投票:0回答:1

我有一个 "经典 "的股票报价sql表。

日期,股票代码,开盘,最高,最低,收盘,成交量。

我想计算一天的变化百分比,所以我需要得到前一天的收盘价和今天的收盘价。

我如何才能在标准Sql中有效地做?

EDIT:我的数据例子。Change value have to be calculated getting previous day close.

enter image description here

谅谅

sql ms-access access
1个回答
2
投票

在任何合理的数据库中,你会简单地使用 lag(). 哦,那就排除了MS Access。 你可以用一个相关的子查询来实现。 下面得到之前的接近。

select q.*,
       (select top (1) q2.close
        from quotes as q2
        where q2.ticker = q.ticker and q2.quotedate < q.quotedate
        order by q2.quotedate desc
       ) as prev_close
from quotes as q;

我不确定你到底是如何计算变化的 但你可以用一个子查询来计算

select q.*,
       (close - prev_close) / prev_close as change_ratio
from (select q.*,
             (select top (1) q2.close
              from quotes as q2
              where q2.ticker = q.ticker and q2.quotedate < q.quotedate
              order by q2.quotedate desc
             ) as prev_close
      from quotes as q
     ) as q;

1
投票
sel ticker,quotedate,open,high,low,close,
100.00*(abs(close-lag(close) over(order by quotedate)))/lag(close) over(order by quotedate) as change 
from table

这将是一个典型的SQL方式,使用滞后性

© www.soinside.com 2019 - 2024. All rights reserved.