【问题标题】:Sum column values over a window based on variable date range (impala)根据可变日期范围(impala)在窗口上对列值求和
【发布时间】:2019-11-19 13:43:55
【问题描述】:

给定一个表格如下:

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

【问题讨论】:

  • 是否保证每个客户每个日期只出现一次?
  • @salman 是的

标签: sql datetime window-functions impala


【解决方案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
      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;

【讨论】:

  • 谢谢 Gordon,但是即使在将 'union all' 更改为 'union' 之后,此查询也会产生重复:我怎样才能有效地摆脱这些?
  • @nicholas 。 . .它在第二个 CTE 中缺少 GROUP BY - 所以它应该已经运行了。这应该可以解决问题。
  • 谢谢。顺便说一句,查询块sum(sum(connections)) over ... 抛出一个错误(Illegal reference to non-materialized slot: tid=7 sid=39),这显然是已知的黑斑羚bug
  • @nicholas 。 . .在这种情况下,您可能需要使用子查询。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多