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

寻求RedShift中分组聚合查询的更简化实现方案

简化后的RedShift聚合查询语句

你可以使用ROLLUP子句直接生成所需的所有分组聚合结果,配合GROUPING()函数将未参与分组的列置为NULL,替代原有的三次查询+UNION ALL的写法,语句如下:

select
    case when grouping(a) = 1 then null else a end as a,
    case when grouping(b) = 1 then null else b end as b,
    case when grouping(c) = 1 then null else c end as c,
    sum(fact) as f
from foo
group by rollup(a, b, c);

逻辑说明

原查询通过三次GROUP BY GROUPING SETS+UNION ALL,实际生成了以下四个分组的聚合结果:

  • 全表聚合(无分组列)
  • 仅按a分组
  • 按a,b分组
  • 按a,b,c分组

ROLLUP(a, b, c)会自动生成上述四个层级的分组(按从右到左的顺序逐步移除分组列),GROUPING(col)函数会返回1表示该列未参与当前分组,0表示参与,用CASE WHEN将未参与分组的列置为NULL,和原查询的输出完全一致。

如果你更倾向于显式指定分组集合,也可以用以下写法,效果相同:

select
    case when grouping(a) = 1 then null else a end as a,
    case when grouping(b) = 1 then null else b end as b,
    case when grouping(c) = 1 then null else c end as c,
    sum(fact) as f
from foo
group by grouping sets(
    (),
    (a),
    (a, b),
    (a, b, c)
);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 22:32:54