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

如何用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

说明

  • 原查询存在三个问题:
    1. 选中了log_date但未将其加入分组字段,违反SQL分组规则;
    2. 错误地按amount分组,需求是按bucket_index单独分组汇总;
    3. 使用count(bucket_index)统计的是行数,而需求是汇总amount的数值总和,应使用sum(amount)。
  • 修正后的查询仅按bucket_index分组,通过sum(amount)计算每组的金额总和,并将结果别名设为amount以匹配期望输出格式,最后按bucket_index排序保证结果顺序。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 04:55:18