»

「Avg()はNULLを除外して平均を算出する」というのを利用する

SQL Server, finance — タグ: , — enjoji.yasujiro @ 11:59 PM

with test as( — @SQL Server2005
select hoge = 20 union all
select hoge = 10 union all
select hoge = 50 union all
select hoge = 0 union all
select hoge = 100
)
select ex1 = avg(hoge)
, ex2 = avg(case when hoge = 0 then null else hoge end)
from test

ex1:( 20 + 10 + 50 + 0 + 100 ) / 5
ex2:( 20 + 10 + 50 + 100 ) / 4

...移動平均を求める場合、例えば25日すべてに株価の値がつくとは限らないので、そういう場合は0をnullに置き換えた上でAVG関数を利用してやれば値が付かなかったレコードも上手に平均値が算出可能のようです。

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