0

我在 Teradata 中下表:

 ranked | data_val 
-------- ----------
 1      | 100
 2      |  30
 2      |  20
 2      |  70

想要下表,其中是按递增值排序avg_val的值的滚动平均值:data_valranked

 ranked | avg_val 
------ ---------
 1      | 100
 2      |  55

我尝试使用:

SELECT 
    ranked
  , AVERAGE(data)val) OVER (
      PARTITION BY NULL 
      ORDER BY ranked ASC
      ROWS UNBOUNDED PRECEDING
      ) AS avg_val
  FROM tbl
;

但我明白了:

 ranked | avg_val 
------ ---------
 1      | 100
 2      |  65
 2      |  50
 2      |  55

这不是我想要的。

如何返回所需的输出?

4

1 回答 1

1

使用窗口函数进行聚合怎么样?

select ranked,
       (sum(sum(data_val)) over (order by ranked rows between unbounded preceding and current row) /
        sum(count(*)) over (order by ranked rows between unbounded preceding and current row)
       )
from t
group by ranked;
于 2019-05-15T18:21:14.077 回答