sql:如何获取上一行/日结束报价?

kr98yfug  于 2021-07-26  发布在  Java
关注(0)|答案(2)|浏览(353)

我有一个用于股票报价的“经典”sql表:
日期,股票,开盘,高,低,收盘,成交量
我想计算一天的百分比变化,所以我需要得到前一天关闭和今天关闭。
如何在标准sql中高效地执行?
编辑:我的数据示例。更改值必须在前一天结束时计算。

谢谢

vh0rcniy

vh0rcniy1#

在任何合理的数据库中 lag() . 哦,好吧,那就排除了ms的访问权限。您可以使用相关的子查询来实现这一点。以下是上一个收盘价:

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;
g52tjvyc

g52tjvyc2#

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

这将是使用lag的典型sql方法

相关问题