sql - 在 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
解决方案
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
推荐阅读
- c - C 中指向字符串管理的指针:替换字符串中的特定字符
- dependency-injection - 使用依赖注入设置 saga 时出现 Masstransit 错误
- r - locator() 如何与图形设备一起使用?
- active-directory - AD 域名迁移到新的 AD 域
- java - 如何让游戏出现一系列硬币?
- docker - 如何在浏览器中查看 Docker 应用程序
- r - 包创建中的 dplyr:group_by 带字符串,不带 group_by_
- mysql - 将字符串转换为时间 sql 或雪花
- php - 使用try catch时如何隐藏PHP错误
- c++ - “class CLASS_EXPORT IKLogin_Export”是什么意思