如何查询当月sum(size)字段的聚合统计数据?
解决方案
方法1:统计当前自然月数据
如果仅需要计算当前月份内各unified_id的累计数据,可直接通过时间范围过滤后聚合:
select unified_id, sum(size) as total_size, count() as total_count from published_file_bandwidth where created_at >= date_trunc('month', current_timestamp) and created_at < date_trunc('month', current_timestamp) + interval '1 month' group by unified_id order by total_count desc;
- 利用
date_trunc获取当月起始时间,结合区间过滤精准定位当月数据,同时匹配表的按月分区特性,保证查询效率。 - 去掉原SQL中的
sample by 1M,避免按分钟采样拆分数据,直接得到全月聚合结果。
方法2:统计所有月份的月度数据
如果需要查看每个unified_id在各个历史月份的统计结果,可按用户+月份维度分组:
select unified_id, date_trunc('month', created_at) as month, sum(size) as total_size, count() as total_count from published_file_bandwidth group by unified_id, month order by month desc, total_count desc;
- 通过
date_trunc('month', created_at)将时间戳截断至月份级别,以此作为分组字段,即可得到每个用户每个月的累计数据。
原SQL问题说明
原SQL中的sample by 1M FILL(LINEAR)是按1分钟间隔对数据采样填充,最终输出的是每分钟的统计值,而非整个月份的总和,这与需求不符,因此需要移除该采样逻辑,改为直接按用户(或用户+月份)聚合。
内容的提问来源于stack exchange,提问作者woss
相关产品推荐
相关产品推荐

