需要每行的过滤条件的列的总和

问题描述 投票:0回答:1

需要获得main_date列与过去365天(一年)之间的缺陷总和,如果有的话,单个ID。并且需要为每一行填充值。

尝试过以下查询并尝试使用CSUM,但它不起作用:

    1)  select sum(Defect) as "sum",Id,MAIN_DT  
      from check_diff 
    where MAIN_DT between  ADD_MONTHS(MAIN_DT,-12) and MAIN_DT group by 2,3;

    2)select    Defect,
    Type1,
    Type2,
    Id,
    MAIN_DT,
    ADD_MONTHS(TIM_MAIN_DT,-12) year_old,
    CSUM(Defect,MAIN_DT)
    from check_diff
    where
        MAIN_DT between ADD_MONTHS(MAIN_DT,-12) and MAIN_DT group by id;

预期产量如下:

Defect     Type1    Type2     Id     main_dt    sum

1            a        a        1     3/10/2017  1
99           a        a        1     4/10/2018  99
0            a        b        1     7/26/2018  99
1            a        b        1     11/21/2018 100
1            a        c        2     12/20/2018 1
sql teradata
1个回答
1
投票

Teradata不支持RANGE用于累积和,但您可以使用Correlated Scalar SUbquery重写它:

select Defect, Id, MAIN_DT,
 ( select sum(Defect) as "sum"
   from check_diff as t2
   where t2.Id = t1.Id
     and t2.MAIN_DT > ADD_MONTHS(t1.MAIN_DT,-12) 
     and t2.MAIN_DT <= t1.MAIN_DT group by 2,3;
 ) as dt
from check_diff as t1

性能可能不好,具体取决于行的总数和每个ID的行数。

热门问题
推荐问题
最新问题