我有这些数据,我希望对字段USAGE_FLAG
求和,但在它降为0时移动或移动到新ID,保持数据集按SU_ID
和WEEK
排序:< / p>
SU_ID WEEK USAGE_FLAG
100 1 0
100 2 7
100 3 7
100 4 0
101 1 0
101 2 7
101 3 0
101 4 7
102 1 7
102 2 7
102 3 7
102 4 0
所以我想创建这个表:
SU_ID WEEK USAGE_FLAG SUM
100 1 0 0
100 2 7 7
100 3 7 14
100 4 0 0
101 1 0 0
101 2 7 7
101 3 0 0
101 4 7 7
102 1 7 7
102 2 7 14
102 3 7 21
102 4 0 0
我使用MSUM()
尝试了GROUP BY
功能,但它不会保留上面我想要的顺序。它将7和周数字组合在一起,这是我不想要的。
任何人都知道这是否可行?我正在使用teradata
答案 0 :(得分:4)
在标准SQL中,可以使用窗口函数来完成运行总和:
select su_id,
week,
usage_flag,
sum(usage_flag) over (partition by su_id order by week) as running_sum
from the_table;
我知道Teradata支持窗口函数,我只是不知道它是否也支持窗口定义中的顺序。
重置总和有点复杂。你首先需要创建每次usage_flag变为0时都会改变的“组ID”。以下在PostgreSQL中有效,我不知道这是否也适用于Teradata:
select su_id,
week,
usage_flag,
sum(usage_flag) over (partition by su_id, group_nr order by week) as running_sum
from (
select t1.*,
sum(group_flag) over (partition by su_id order by week) as group_nr
from (
select *,
case
when usage_flag = 0 then 1
else 0
end as group_flag
from the_table
) t1
) t2
order by su_id, week;
答案 1 :(得分:3)
尝试下面的代码,使用RESET功能它工作正常。
select su_id,
week,
usage_flag,
SUM(usage_flag) OVER (
PARTITION BY su_id
ORDER BY week
RESET WHEN usage_flag < /* preceding row */ SUM(usage_flag) OVER (
PARTITION BY su_id ORDER BY week
ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING)
ROWS UNBOUNDED PRECEDING
)
from emp_su;
答案 2 :(得分:0)
请尝试以下SQL:
select su_id,
week,
usage_flag,
SUM(usage_flag) OVER (PARTITION BY su_id ORDER BY week
RESET WHEN usage_flag = 0
ROWS UNBOUNDED PRECEDING
)
from emp_su;
这里 RESET WHEN usage_flag = 0 会在sum_using_flag减少为0时重置总和