代码改变世界

postgresql中的rollup

2020-07-10 15:11  abce  阅读(1943)  评论(0编辑  收藏  举报

在postgresql中,rollup是group by的子句,提供了多个分组集的简便方式。分组集(grouping set)是用户用于分组的一组列的集合。

与cube语句不同,rollup不会在指定的列上产生所有可能的分组集。

rollup假设输入的列上有层次结构,根据层次结构生成分组集。这就是为什么rollup会经常用于生成报表的grang total和subtotals。

例如,cube(c1,c2,c3)会生成八个可能的分组集:

()
(c1)
(c2)
(c3)
(c1,c2)
(c1,c3)
(c2,c3)
(c1,c2,c3)

然而,rollup(c1,c2,c3)只会生成四个分组集,假设层次关系是c1>c2>c3:

()
(c1)  
(c1,c2)
(c1,c2,c3)

常见的用途是使用rollup来计算根据year、month、date进行聚合的数据,设定层次关系是year>month>date。

以下是语法:

select c1,c2,c3,aggregate(c4)
from table_name
group by rollup(c1,c2,c3);

也可以执行部分rollup操作来减少subtotals的生成:

select c1,c2,c3,aggregate(c4)
from table_name
group by c1,
rollup(c1,c2,c3);