athena/presto sql为每天的历史数据聚合信息

zphenhs4  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(420)

我有下面的示例表,它使用变更数据捕获来捕获历史信息:

  1. id cdc_date cdc_flag active name
  2. 1 2020-07-12 Insert true a
  3. 2 2020-07-12 Insert true b
  4. 3 2020-07-12 Insert true c
  5. 4 2020-07-12 Insert true d
  6. 1 2020-07-13 Update false a
  7. 3 2020-07-13 Update true c_changed
  8. 4 2020-07-14 Deleted true d

对于任何列的更新,都会向表中添加一个新条目。因此,存在同一id的多个版本。
我需要找到在每个cdc\ U日期当天或之前处于活动状态的ID的总数。
期望输出:

  1. cdc_date count_active
  2. 2020-07-12 4
  3. 2020-07-13 4
  4. 2020-07-14 3

我无法在athena中为所需的输出形成查询,因为没有过程或递归查询可用。
以下是我计算某个特定日期的活动ID的方法:

  1. id cdc_date cdc_flag active rank
  2. 1 2020-07-12 Insert true 2
  3. 2 2020-07-12 Insert true 1
  4. 3 2020-07-12 Insert true 2
  5. 4 2020-07-12 Insert true 2
  6. 1 2020-07-13 Update false 1
  7. 3 2020-07-13 Update true 1
  8. 4 2020-07-14 Deleted true 1
  1. Select date('2020-07-14') as cdc_date, sum(if(active = 'true',1,0)) as count_active from
  2. (Select *, rank over (partition by id over cdc_date desc) as rank)
  3. where rank = 1 and cdc_flag != 'Deleted' and cdc_date <= date('2020-07-14')

我需要为每个cdc\u日期这样做,但排名需要为每个cdc\u日期重新计算,我无法想到一个没有过程或递归的解决方案。
请建议使用athena/presto sql解决此问题。

exdqitrt

exdqitrt1#

可以将累积和与聚合一起使用:

  1. select cdc_date,
  2. sum(sum(case when cdc_flag = 'active' then 1
  3. when cdc_flag = 'Deleted' then -1
  4. else 0
  5. end)
  6. ) over (order by cdc_date) as num_actives
  7. from t
  8. group by cdc_date;

相关问题