In standard SQL, the current amount can be executed using the window processing function:
select su_id, week, usage_flag, sum(usage_flag) over (partition by su_id order by week) as running_sum from the_table;
I know that Teradata supports window functions, I just don’t know if it supports order in the window definition.
Resetting the amount is a bit trickier. First you need to create “group identifiers” that change every time use_flag goes to 0. The following works in PostgreSQL: I don’t know if this works in 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;
a_horse_with_no_name
source share