基于可变日期范围(Impala)在窗口上汇总列值

给出如下表:

client_id   date            connections
---------------------------------------
121438297   2018-01-03      0
121438297   2018-01-08      1
121438297   2018-01-10      3
121438297   2018-01-12      1
121438297   2018-01-19      7
363863811   2018-01-18      0
363863811   2018-01-30      5
363863811   2018-02-01      4
363863811   2018-02-10      0

我正在寻找一种有效的方法来汇总在当前行之后的x天之内发生的连接数(当前行包括在总和中),并按client_id进行分区。

如果x=6,则输出表将导致:

client_id   date            connections     connections_within_6_days
---------------------------------------------------------------------
121438297   2018-01-03      0               1        
121438297   2018-01-08      1               5     
121438297   2018-01-10      3               4     
121438297   2018-01-12      1               1                       
121438297   2018-01-19      7               7
363863811   2018-01-18      0               0
363863811   2018-01-30      5               9
363863811   2018-02-01      4               4
363863811   2018-02-10      0               0

关注点:

  1. 我不想添加所有丢失的日期,然后执行滑动窗口以计算后面的x行,因为我的表已经很大。

  2. 我正在使用Impala,但不支持range between interval 'x' days following and current row

Qwea521 回答:基于可变日期范围(Impala)在窗口上汇总列值

通用解决方案在多个时期内都有些麻烦,但是您可以使用多个CTE来支持该解决方案。想法是根据进出计数时“取消透视”计数,然后使用累积和。

所以:

with conn as (
      select client_id,date,connections
      from t
      union all
      select client_id,date + interval 7 day,-connections
      from t
     ),conn1 as (
      select client_id,sum(sum(connections)) over (partition by client_id order by date) as connections_within_6_days
      from t
      group by client_id,date
     )
select t.*,conn1. connections_within_6_days
from t join
     conn1
     on conn1.client_id = t.client_id and
        conn1.date = t.date;
本文链接:https://www.f2er.com/3073061.html

大家都在问