postgresql 仅当空值的特定百分比时才使用滚动平均值

mwg9r5ms  于 2023-08-04  发布在  PostgreSQL
关注(0)|答案(1)|浏览(109)

我需要得到一个值的滚动平均值在8天前考虑的记录。但是,我希望它只计算当我有至少6个非空值的8个记录(8天)。换句话说,只有当至少有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或其他值?

1hdlvixo

1hdlvixo1#

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

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

字符串

相关问题