在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);