基于可变日期范围(impala)的窗口上的总列值

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

给出如下表:

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

sql datetime window-functions impala
1个回答
1
投票

通用解决方案在多个时期内都有些麻烦,但是您可以使用多个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, date,
             sum(sum(connections)) over (partition by client_id order by date) as connections_within_6_days
      from t
     )
select t.*, conn1. connections_within_6_days
from t join
     conn1
     on conn1.client_id = t.client_id and
        conn1.date = t.date;
© www.soinside.com 2019 - 2024. All rights reserved.