SQL Server 2012中的平均真实范围

时间:2018-02-25 01:00:16

标签: sql-server-2012 max min

我有一个表t,其中包含date, ticker, open, high, low, close列。

declare @t table 
           (
               [Datecol] date,
               Ticker varchar(10),
               [open] decimal (10,2),
               [high] decimal (10,2), 
               [low] decimal (10,2),
               [close] decimal(10,2)
           )

insert into @t values
('20180215', 'ABC', '122.01', '125.76', '118.79' , '123.29')
,('20180216', 'ABC', '123.02', '130.62', '119.94' , '128.85')
,('20180217', 'ABC', '131.03', '139.80', '129.42' , '136.75')
,('20180218', 'ABC', '136.40', '137.95', '124.32' , '127.38')
,('20180219', 'ABC', '127.24', '138.52', '126.70' , '137.47')
,('20180220', 'ABC', '137.95', '142.01', '127.86' , '128.36')
,('20180215', 'JKL', '9.94', '10.30', '9.77' , '10.17')
,('20180216', 'JKL', '10.15', '10.24', '9.70' , '10.02')
,('20180217', 'JKL', '10.01', '10.18', '9.93' , '10.15')
,('20180218', 'JKL', '10.16', '10.20', '9.23' , '9.38')
,('20180219', 'JKL', '9.37', '9.79', '9.36' , '9.68')
,('20180220', 'JKL', '9.69', '10.01', '9.26' , '9.28')

我有兴趣计算每个股票代码的每日平均真实范围(ATR)。

ATR = Max(今日高位,昨日收盘价) - 最低价(今日低点,昨日收盘价)

使用LAG功能,我可以在昨天结束:

SELECT 
    *,
    ((LAG([close], 1) OVER (PARTITION BY Ticker ORDER BY [Datecol])) - 0) * 1 AS 'yest_close'
FROM 
    @t t


Datecol    Ticker  open     high    low     close   yest_close
--------------------------------------------------------------
2018-02-15  ABC    122.01   125.76  118.79  123.29   NULL
2018-02-16  ABC    123.02   130.62  119.94  128.85  123.29
2018-02-17  ABC    131.03   139.80  129.42  136.75  128.85
2018-02-18  ABC    136.40   137.95  124.32  127.38  136.75
2018-02-19  ABC    127.24   138.52  126.70  137.47  127.38
2018-02-20  ABC    137.95   142.01  127.86  128.36  137.47
2018-02-15  JKL      9.94    10.30    9.77   10.17   NULL
2018-02-16  JKL     10.15    10.24    9.70   10.02   10.17
2018-02-17  JKL     10.01    10.18    9.93   10.15   10.02
2018-02-18  JKL     10.16    10.20    9.23    9.38   10.15
2018-02-19  JKL      9.37     9.79    9.36    9.68    9.38
2018-02-20  JKL      9.69    10.01    9.26    9.28    9.68

我如何获得最大值(今天的高点,昨天的收盘价)?

0 个答案:

没有答案