You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Athena中对WITH子查询的true/false统计结果求和?

解决Athena查询结果聚合问题

需求说明

现有两个独立子查询(group1和group2),各自的数据源、WHERE过滤条件以及matches的判断逻辑均不同,需要将两个子查询中同matches值的计数相加,得到最终聚合结果:

  • true对应计数总和:10 + 30 = 40
  • false对应计数总和: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

逻辑说明

  1. 为两个子查询的计数字段统一命名为cnt,方便后续聚合操作
  2. 使用union all合并两个子查询的结果集(保留所有行,包含重复的matches值)
  3. 对合并后的数据集按matches字段分组,通过sum(cnt)计算同matches值的计数总和

内容的提问来源于stack exchange,提问作者toy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 06:09:54