9

我有这些数据,我想对字段求和,USAGE_FLAG但在它下降到 0 或移动到新 ID 时重置,保持数据集按SU_IDand排序WEEK

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

4

3 回答 3

6

在标准 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 支持窗口功能,我只是不知道它是否还支持窗口定义中的 order by。

重置总和有点复杂。您首先需要创建每次使用标志变为 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;
于 2012-12-11T11:51:57.793 回答
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;
于 2014-06-19T11:28:12.743 回答
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 usage_flag 降至 0 时重置 sum

于 2017-07-06T08:19:30.817 回答