首页 > 解决方案 > 在 pyspark 中使用窗口函数时添加过滤器

问题描述

我有如下数据。数据以 parquet 格式保存在 Datalake 中,按 order_dt 分区。

客户编号 id1 总和1 final_sum order_dt
123 1 10 无效的 9 月 7 日
123 1 27 无效的 9 月 7 日
123 1 30 无效的 9 月 6 日
123 1 25 无效的 9月12日
123 1 40 28 9 月 14 日

我正在尝试使用 pyspark 中的窗口功能来选择数据。我的要求如下。

对于每个客户编号和 ID 组合,选择具有以下条件的数据以及基本记录。

  1. order_dt < order_dt-7
  2. 总和 <= final_sum

第一条记录在给定数据集中没有任何匹配记录。但是最后一条记录在 rec_nums 1,2 和 3 中有匹配项。其中,recs 2 和 3 被过滤,因为它们不匹配第二个条件。所以输出看起来像。

客户编号 id1 总和1 final_sum order_dt_t1 总和2 order_dt_t2
123 1 40 28 9 月 14 日 10 9 月 7 日
123 1 40 28 9 月 14 日 27 9 月 7 日

我使用 window.partitionBy 函数和 orderBy.ranegebetween 子句来获得第一个条件。但我无法在 orderBy 中指定第二个条件。

我尝试编写一个自联接查询。但这需要很长时间才能运行。数据量为2000万。因此,自联接查询可以产生大量数据,并且数量增长到数十亿。以下是我使用的查询。相当简单的一个。但可能不是最有效的。

select t1.cust_num,t1.id1,t1.sum1,t1.final_sum,t1.order_dt as order_dt_t1,t2.sum_t2,t2.order_dt as order_dt_t2
from tab1 as t1 left outer join tab1 as t2
on
t1.cust_num=t2.cust_num and
t1.id1=t2.id1 and
t2.order_dt<date_sub(t1.order_dt,3) and
t1.sum1<t2.final_sum

有没有更有效的方法来解决这个问题?

标签: pysparkapache-spark-sql

解决方案


推荐阅读