如何在Athena中对WITH子查询的true/false统计结果求和?
解决Athena查询结果聚合问题
需求说明
现有两个独立子查询(group1和group2),各自的数据源、WHERE过滤条件以及matches的判断逻辑均不同,需要将两个子查询中同matches值的计数相加,得到最终聚合结果:
true对应计数总和:10 + 30 = 40false对应计数总和:20 + 40 = 60
修改后的查询语句
with group1 as ( select contains(array1, 'element_1') AS matches, count(*) as cnt from -- from statement where -- where statement group by 1 ), group2 as ( select contains(array1, 'element_2') AS matches, count(*) as cnt from -- from statement1 where -- where statement1 group by 1 ) select matches, sum(cnt) as total_count from ( select matches, cnt from group1 union all select matches, cnt from group2 ) combined group by matches
逻辑说明
- 为两个子查询的计数字段统一命名为
cnt,方便后续聚合操作 - 使用
union all合并两个子查询的结果集(保留所有行,包含重复的matches值) - 对合并后的数据集按
matches字段分组,通过sum(cnt)计算同matches值的计数总和
内容的提问来源于stack exchange,提问作者toy
相关产品推荐
相关产品推荐

