如何在Teradata中按排名(而非行)计算滚动平均值?

时间:2019-05-15 18:19:44

标签: sql average teradata ansi-sql rolling-average

具有 Teradata中的下表:

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

想要下表,其中avg_valdata_val值的滚动平均值,通过递增ranked值来排序:

 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

这不是我想要的。

如何返回所需的输出?

1 个答案:

答案 0 :(得分: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;