如何在 Teradata 中按排名(而不是行)计算滚动平均值?
How to compute a rolling average by rank (not row) in Teradata?
我在 Teradata 中有以下table:
ranked | data_val
-------- ----------
1 | 100
2 | 30
2 | 20
2 | 70
我想要以下table,其中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
这不是我想要的。
如何return 获得所需的输出?
使用 window 函数聚合怎么样?
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;
我在 Teradata 中有以下table:
ranked | data_val
-------- ----------
1 | 100
2 | 30
2 | 20
2 | 70
我想要以下table,其中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
这不是我想要的。
如何return 获得所需的输出?
使用 window 函数聚合怎么样?
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;