我具有 Teradata中的下表:
ranked | data_val
-------- ----------
1 | 100
2 | 30
2 | 20
2 | 70
我想要下表,其中avg_val
是data_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
这不是我想要的。
如何返回所需的输出?
答案 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;