您好,感谢您的帮助。我有下表:
create table temp_vol (symbol nchar(10), dseqkey int, volume float)
这里有一些值:
symbol dseqkey volume (no commas in the actual values)
C 20672 422,764,512
F 20672 47,144,600
F 20671 51,695,000
C 20671 371,950,496
F 20670 48,680,600
C 20670 654,208,512
C 20669 626,121,600
F 20669 93,489,504
C 20668 712,674,304
我正在寻找的输出是每个符号的2天简单移动平均线((音量dseqkey +音量dseqkey-1)/ 2),每个dseqkey。我可以通过一个dseqkey获得所有符号的移动平均线。我可以通过1个符号获得所有dseqkeys的移动平均线。我似乎无法让两者一起工作。
答案 0 :(得分:2)
您可以使用row_number()
为每行添加一个数字。这允许您查找上一行。针对3值移动平均线编辑的示例:
; with numbered as
(
select ROW_NUMBER() over (partition by symbol order by dseqkey) rn
, *
from temp_vol
)
select cur.symbol
, cur.dseqkey
, avg(window.volume) as MovingAverage
from numbered cur
join numbered window
on cur.symbol = window.symbol
and window.rn between cur.rn - 2 and cur.rn
group by
cur.symbol
, cur.dseqkey
order by
cur.symbol
, cur.dseqkey
打印:
symbol dseqkey MovingAverage
---------- ----------- ----------------------
C 20668 712674304
C 20669 669397952
C 20670 664334805,333333
C 20671 550760202,666667
C 20672 482974506,666667
F 20669 93489504
F 20670 71085052
F 20671 64621701,3333333
F 20672 49173400
测试数据:
if OBJECT_ID('temp_vol') is not null
drop table temp_vol
create table temp_vol (symbol nchar(10), dseqkey int, volume float)
insert temp_vol values
('C', 20672, 422764512 ),
('F', 20672, 47144600 ),
('F', 20671, 51695000 ),
('C', 20671, 371950496 ),
('F', 20670, 48680600 ),
('C', 20670, 654208512 ),
('C', 20669, 626121600 ),
('F', 20669, 93489504 ),
('C', 20668, 712674304 )
答案 1 :(得分:0)
我不在带有数据库引擎的计算机上,所以我无法确定这一点:
在评论后更新
SELECT A.symbol, A.dseqkey, AVG(B.volume) MovingAverage
FROM temp_vol A
LEFT JOIN temp_vol B
ON A.symbol = B.symbol AND A.dseqkey BETWEEN B.dseqkey - 30 AND B.dseqkey
GROUP BY A.symbol, A.dseqkey