首页 > 解决方案 > 基于 Pyspark 中其他值的一列的条件聚合

问题描述

尽管我在类似的行中看到了一个问题,但这不符合我的目的。所以把它贴在这里,期待得到答案。我有 2 个 pyspark 数据框:客户每周在产品上的花费

在此处输入图像描述

  1. 产品销售的第一周和最后一周 在此处输入图像描述

我需要根据产品的第一周和最后一周的销售情况来获取客户在每个产品对应的类别中的支出。例如对应产品 W,因为它只在第 2 周出现,所以我只需要考虑客户在第 2 周的类别支出 在此处输入图像描述

我正在努力解决它,但没有运气。寻找建议。

标签: sqlpyspark

解决方案


我想我明白了。这比我想象的要复杂,但我认为这可以满足您的要求:

select t1.*, t2.category_spend
from table1 t1 join
     (select t2.product, sum(t1.spend) as category_spend
      from table1 t1 join
           table2 t2
           on t1.week between t2.weekstart between t2.weekend
      group by t2.product
     ) t2w
     on t2w.product = t1.product;

编辑:

根据您的评论,逻辑基本相同。这个customer问题并没有区分它,所以它可以被包含在“任何地方”:

select t1.*, t2.category_spend
from table1 t1 join
     (select t1.customer, t2.product, sum(t1.spend) as category_spend
      from table1 t1 join
           table2 t2
           on t1.week between t2.weekstart between t2.weekend
      group by t2.product, t1.customer
     ) t2w
     on t2w.product = t1.product and t2w.customer = t1.customer;

推荐阅读