You can give each line a number with row_number(). This allows you to search for previous lines. Example edited for a 3-digit moving average:
; 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
Fingerprints:
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
Test data:
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 )