sql - Athena/Presto SQL 每天汇总历史数据信息
问题描述
我有以下示例表,它使用变更数据捕获来捕获历史信息:
id cdc_date cdc_flag active name
1 2020-07-12 Insert true a
2 2020-07-12 Insert true b
3 2020-07-12 Insert true c
4 2020-07-12 Insert true d
1 2020-07-13 Update false a
3 2020-07-13 Update true c_changed
4 2020-07-14 Deleted true d
对于任何列的更新,都会将新条目添加到表中。因此,存在同一个 ID 的多个版本。
我需要找到在每个 cdc_date 上或之前处于活动状态的 id 总数。
期望的输出:
cdc_date count_active
2020-07-12 4
2020-07-13 4
2020-07-14 3
由于没有可用的过程或递归查询,我无法在Athena中为所需的输出形成查询。
以下是我计算某个特定日期的活动 ID 的方法:
id cdc_date cdc_flag active rank
1 2020-07-12 Insert true 2
2 2020-07-12 Insert true 1
3 2020-07-12 Insert true 2
4 2020-07-12 Insert true 2
1 2020-07-13 Update false 1
3 2020-07-13 Update true 1
4 2020-07-14 Deleted true 1
Select date('2020-07-14') as cdc_date, sum(if(active = 'true',1,0)) as count_active from
(Select *, rank over (partition by id over cdc_date desc) as rank)
where rank = 1 and cdc_flag != 'Deleted' and cdc_date <= date('2020-07-14')
我需要为每个 cdc_date 执行此操作,但需要为每个 cdc_date 重新计算排名,我无法想到没有过程或递归的解决方案。
请使用 Athena/Presto SQL 提出解决方案。
解决方案
您可以将累积和与聚合一起使用:
select cdc_date,
sum(sum(case when cdc_flag = 'active' then 1
when cdc_flag = 'Deleted' then -1
else 0
end)
) over (order by cdc_date) as num_actives
from t
group by cdc_date;
推荐阅读
- dart - 颤振 onClosing 回调 showModalBottomSheet
- spring-boot - 我是否需要 webstarter 才能仅使用 RestController 注释?
- sql-server - ignore_dup_key = on 在 SQL Server 中不会忽略表中的重复项
- docker-compose - 如何在 docker-compose 中转义 #
- java - 检查账户不存在时出现空指针异常 - Spring+Thymeleaf
- python - 如果相邻单元格中的条件为真,则更新值
- c# - 如何对“HttpContext.Current.Request.LogonUserIdentity.Name”进行单元测试?
- python - AttributeError:模块“lightgbm”没有属性“数据集”
- javascript - WKWebView 在脚本加载之前不加载 HTML 内容
- python - 如何从文件夹中随机选择一个文件而不将所有文件读入内存