SQL Server滚动平均值

时间:2018-04-01 00:20:01

标签: sql-server sql-server-2014 rolling-average

select
    Date, [Close],
    avg([close]) over (order by date asc rows 4 preceding) as MA10
from 
    dbo.APPL

此查询返回滚动4天股票价格平均值。但是,如果前几天少于4,我想将值显示为NULL

如何在SQL Server中调整它?

1 个答案:

答案 0 :(得分:-1)

我认为JeffUK意味着做这样的事情:

select
    Date, [Close],
    case when days >= 4 then MA10 end as MA10
from
(
    select
        Date, [Close],
        avg([close]) over (order by date asc rows 4 preceding) as MA10,
        count([close]) over (order by date asc rows 4 preceding) as days
    from 
        dbo.APPL

) X