首页 > 解决方案 > 在 pyspark 中查找过去 n 天内出现的 id

问题描述

我有这个下面的数据集,想计算过去 n 天 id 的出现。我试图用 pyspark 中的 windows 函数来做到这一点

ID 日期
123 2021 年 7 月 14 日
123 2021 年 7 月 13 日
123 2021 年 7 月 11 日
123 2021 年 6 月 1 日
234 2021 年 7 月 14 日
234 2021 年 7 月 1 日
234 2020 年 1 月 13 日
234 2021 年 6 月 1 日

预期输出:

ID 过去 5 天内发生 过去 10 天内发生
123 2 3
234 1 2

下面是我尝试过的代码

select * ,
count(id) over(
  partition by id 
  order by cast(date as timestamp)
  range between interval 5 days preceding and current row
)as id_cnt
from
t1

标签: sqlpysparkapache-spark-sqlwindow-functions

解决方案


select 
   id
   , count(*) 'occurrence in last 10 days'
   , count(when date >= today - interval 5 dyas then 1 end) 'occurrence in last 5 days', 
from t1
where date between today and today - interval 10 days
group by id

推荐阅读