蜂巢-使用先前的列值条件获取累积总和

时间:2019-05-01 11:37:46

标签: sql hive hiveql

输入表t1:

enter image description here

需要的输出:

enter image description here

详细说明: 如果fg和x的值为“ Carry”,则z的值应等于前一行+ 1的计算得出的z的值。否则z应当等于0。 按照示例,对于第一行,我们将z的先前计算值视为0,然后将其递增1,因为fg和x都等于“ Carry”。

在第二行中,fg和x均为“ Carry”,并且上一行的计算值是1,而不是将其加1得出2。

在第三行中,由于fg和x都不等于“ Carry”,因此z值为0。

我尝试使用SUM(),LAST_VALUE()函数等,但是在这种情况下似乎没有任何效果。我基本上是在试图复制SAS在HIVE中的保留功能。任何帮助将不胜感激。

注意:订购是通过id列完成的。

2 个答案:

答案 0 :(得分:0)

您可以使用累积和定义组。然后使用row_number()。在以下代码中,?用于指定顺序的列:

select t.*,
       (case when fg = 'Carry' and x = 'Carry'
             then row_number() over (partition by id, grp, fg, x order by ?)
             else 0
        end) as z
from (select t.*,
             sum(case when fg = 'Carry' and x = 'Carry' then 0 else 1 end) over (partition by id order by ?) as grp
      from t
     ) t;

Here是db <>小提琴。请注意,这使用的是Postgres而不是Hive,但这不会有所不同。

答案 1 :(得分:0)

您应该创建一个变量,并检查fg和x是否均为 Carry ,然后增加变量值,否则将其分配为0。

SELECT id, fg, x, if(fg='Carry' and x = 'Carry', @a:=@a+1, @a:=0) as z from t1, (SELECT @a:= 0) as a;