根据可变日期范围 (impala) 对 window 的列值求和

Sum column values over a window based on variable date range (impala)

给定一个 table 如下:

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 则输出 table 将导致:

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. 我不想添加所有缺失的日期,然后执行滑动 window 计算后面的 x 行,因为我的 table 已经非常大了。

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

通用的解决方案对于多个周期有点麻烦,但是你可以使用多个CTE来支持。这个想法是"unpivot"根据他们进出的时间进行计数,然后使用累积总和。

所以:

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, date,
             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;