»

memo for MovingAverage

SQL Server, finance — enjoji.yasujiro @ 12:16 AM

with tbl as( /* @SQL Server */
select code
, nm = RANK() OVER (PARTITION BY code ORDER BY period DESC)
, period
, price
from (
select code= 1301 , period = 20080430,Price= 10 union all
select code= 1301 , period = 20080501,Price= 20 union all
select code= 1301 , period = 20080502,Price= 30 union all
select code= 1301 , period = 20080507,Price= 40 union all
select code= 1301 , period = 20080508,Price= 50 union all
select code= 1301 , period = 20080509,Price= 60 union all
select code= 1301 , period = 20080512,Price= 70 union all
select code= 1301 , period = 20080513,Price= 80 union all
select code= 1301 , period = 20080514,Price= 90 union all
select code= 7203 , period = 20080501,Price= 11 union all
select code= 7203 , period = 20080502,Price= 22 union all
select code= 7203 , period = 20080507,Price= 33 union all
select code= 7203 , period = 20080508,Price= 44 union all
select code= 7203 , period = 20080509,Price= 55 union all
select code= 7203 , period = 20080512,Price= 66 union all
select code= 7203 , period = 20080513,Price= 77 union all
select code= 7203 , period = 20080514,Price= 88 union all
select code= 7203 , period = 20080515,Price= 99
) x
)select a.code
, a.nm
, a.period
, a.price
, MovingAverage=avg(b.price)
/*
, a.period
, a.price
, b.nm
, b.period
, b.price
*/
from tbl a
cross join tbl b
where a.code= b.code
and a.nm+5 > b.nm
and a.nm <= b.nm
group by a.code
, a.nm
, a.period
, a.price
having count(*)=5
order by a.code
, a.nm desc

1 件のコメント »

  1. [...] ...移動平均を求める場合に例えば25日すべてに株価の値がつくとは限らないので、そういう場合を考慮して0をnullにした上でAVG関数を利用してやればOKっぽい。 [...]

このコメント欄の RSS フィード TrackBack URI

コメントをどうぞ

This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License.
(c) 2009 鎌倉橋日記 | powered by WordPress with Barecity