仅当空值达到特定百分比时才滚动平均值

问题描述 投票:0回答:1

我需要获取所考虑记录之前 8 天的滚动平均值。 但是,我希望仅在记录的 8 个值(8 天)中至少有 6 个非空值时才计算它。换句话说,仅当您拥有至少 75% 的有效值时,才计算 8 天的滚动平均值。

这是我的查询:

select
    case when
        row_number() over (order by DATEX) > 8
        then
            avg(VALUEX) OVER (
                ORDER BY DATEX DESC
                ROWS BETWEEN 1 following AND 8 FOLLOWING
            )
        else null end
from (
    select *
    from TABLEX
) s

如何才能使其仅当我的 8 个先前值中至少有 6 个非空值时才返回滚动平均值,并在我的非空值少于 6 个时返回 null 或其他值?

sql postgresql where-clause partition rolling-average
1个回答
0
投票

只需计算非空值的数量并根据该数量进行过滤(如果这是您想要的):

select case when cnt >=6 then avg else null end as avg 
from (
    select
        count(VALUEX) OVER w as cnt
        , avg(VALUEX) OVER w as avg
    from TABLEX
    window w as (ORDER BY DATEX DESC ROWS BETWEEN 1 following AND 8 FOLLOWING)
) s 

© www.soinside.com 2019 - 2024. All rights reserved.