使用Oracle Analytics更改任一列值时重置运行总计

时间:2016-03-26 15:20:24

标签: oracle

我想在视图中添加一列,以保持Value列的运行总计。当Cat A或Cat B在行中发生变化时,此列必须重置运行总计。 所以输出数据必须是这样的: -

CAT A  CAT B    Value   Running Total
=====  =====    =====   =============
0        1       15 
0        1       235 
0        1       306      556
0        0        
1        2       85        85
1        1       105      105 
0        2       600
0        2       70       670
0        3       564
0        3       101      665
0        1       30        30

1 个答案:

答案 0 :(得分:1)

首先,您需要一个列来指定运行总和的顺序。我将假设这被称为id

其次,您似乎有某些逻辑在某些行上没有值。目前尚不清楚这种逻辑是什么。适当的"运行总和"将在所有行上定义。

然后,您可以使用lag()sum()来定义群组并使用" analytic" sum()用于运行总和:

select t.cata, t.catb, t.value,
       sum(value) over (partition by grp order by id) as runningsum
from (select t.*,
             sum(case when cata = prev_cata and catb = prev_catb then 0
                      else 1
                  end) over (order by id) as grp
      from (select t.*, lag(cata) over (order by id) as prev_cata,
                   lag(catb) over (order by id) as prev_catb
            from t
           ) t
     ) t;