如何用SparkSQL 2.0按bucket_index字段汇总amount数值?
SparkSQL 2.0 按bucket_index汇总amount的查询修正
需求
按bucket_index字段对amount数值进行汇总统计。
原数据表结构及数据
log_date, bucket_index, amount 2022-11-18, 1, 1 2022-11-18, 2, 1 2022-11-18, 2, 1 2022-11-18, 3, 1 2022-11-18, 3, 1
当前错误查询
select log_date, count(bucket_index) from data_table group by bucket_index, amount order by bucket_index, amount
期望结果
bucket_index, amount 1, 1 2, 2 3, 2
正确查询语句
select bucket_index, sum(amount) as amount from data_table group by bucket_index order by bucket_index
说明
- 原查询存在三个问题:
- 选中了
log_date但未将其加入分组字段,违反SQL分组规则; - 错误地按
amount分组,需求是按bucket_index单独分组汇总; - 使用
count(bucket_index)统计的是行数,而需求是汇总amount的数值总和,应使用sum(amount)。
- 选中了
- 修正后的查询仅按
bucket_index分组,通过sum(amount)计算每组的金额总和,并将结果别名设为amount以匹配期望输出格式,最后按bucket_index排序保证结果顺序。
内容的提问来源于stack exchange,提问作者recap
相关产品推荐
相关产品推荐

