天睿数据。如何对一个组内的所有值求和?
Teradata. How to sum all values within a group?
我的初始 table 看起来像这样
id value
1 20
1 50
1 30
2 60
2 5
2 35
我需要以下结果 table
id value cum | ( this is explanation not a field)
_ _ _ _ _ _ _ _ __ _ _ _ _ _ _ _ __ _ _ _ _ _ _ _ __ _ _ _ _ _ _ _ _
1 20 20 | (0 + 20 = 20)
1 30 50 | (30 + 20 = 50)
1 50 100 | (50 + 50 = 100)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ __ _ _ _ _ _ _ _ __ _ _ _ _ _ _ _ _
2 5 5 | (0 + 5 = 5)
2 35 40 | (5 + 35 = 40)
2 60 100 | (40 + 60 = 100)
逻辑是
1)ORDER
原tableBY value ASC
2) SUM
将所有先前的值加起来,产生累积的 cum
字段。所以 cum
列是所有 value
小于当前 value
的 SUM
。
我只需要在没有存储过程的情况下使用 sql 执行此操作
我该怎么做?
嗯,你描述一个累计和:
sum(value)
over (partition by id
order by values
rows unbounded preceding)
Teradata 中需要 rows unbounded preceding
,因为它默认为 rows unbounded preceding and unbounded following
(一个 Group Sum),这与 Standard SQL 的默认值 range unbounded preceding
.
我的初始 table 看起来像这样
id value
1 20
1 50
1 30
2 60
2 5
2 35
我需要以下结果 table
id value cum | ( this is explanation not a field)
_ _ _ _ _ _ _ _ __ _ _ _ _ _ _ _ __ _ _ _ _ _ _ _ __ _ _ _ _ _ _ _ _
1 20 20 | (0 + 20 = 20)
1 30 50 | (30 + 20 = 50)
1 50 100 | (50 + 50 = 100)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ __ _ _ _ _ _ _ _ __ _ _ _ _ _ _ _ _
2 5 5 | (0 + 5 = 5)
2 35 40 | (5 + 35 = 40)
2 60 100 | (40 + 60 = 100)
逻辑是
1)ORDER
原tableBY value ASC
2) SUM
将所有先前的值加起来,产生累积的 cum
字段。所以 cum
列是所有 value
小于当前 value
的 SUM
。
我只需要在没有存储过程的情况下使用 sql 执行此操作
我该怎么做?
嗯,你描述一个累计和:
sum(value)
over (partition by id
order by values
rows unbounded preceding)
Teradata 中需要 rows unbounded preceding
,因为它默认为 rows unbounded preceding and unbounded following
(一个 Group Sum),这与 Standard SQL 的默认值 range unbounded preceding
.