select 列1,sum(计算列) from table_name t group by rollup(列1,列2..列n);
会返回 【列1】【列1,列2】【列1,列2,列3】...【列1,列2,列3...列n】的每种排列的sum(计算列)和 全部记录的sum(计算列) ,一共是n+1种排列
select 列1,...列n,sum(计算列) from table_name t group by cube(列1,列2...列n);
会返回 【列1】,【列2】,【列3】,【列4】...【列n】,【列1,列2】,【列1,列3】,【列1,列4】...【列1,列n】,【列2,列3】,【列2,列4】...【列2,列n】...【列n-1,列n】 每个分组的sum(计算列) 和 全部记录的sum(计算列),一共是 C 0 n+C 1 n+C 2 n+...C n n种排列。
如下演示(因为多条数据会比较杂乱,不易说明,所以我们选择极端情况,就认为表里只有一条记录):
--group by
select flag1,flag2,flag3,flag4,sum(flag5)
from (select 'column1' as flag1,
'column2' as flag2,
'column3' as flag3,
'column4' as flag4,
1 flag5
from dual)
group by flag1,flag4;
from (select 'column1' as flag1,
'column2' as flag2,
'column3' as flag3,
'column4' as flag4,
1 flag5
from dual)
group by flag1,flag4;
--group by cobe
select flag1,sum(flag5)
from (select 'column1' as flag1,
1 flag5
from dual)
group by cube(flag1,flag4);
from (select 'column1' as flag1,
1 flag5
from dual)
group by cube(flag1,flag4);
--group by rollup
select flag1,
1 flag5
from dual)
group by rollup(flag1,flag4);
1 flag5
from dual)
group by rollup(flag1,flag4);
rollup的分组排列种类为 n+1 ,上述例子group by 为4列,所以 是 4+1 种情况
cube的分组排列种类是 C 0 n+C 1 n+C 2 n+...C n n 上述例子group by 为4列,所以是C 0 4+C 1 4+C 2 4+C 3 4+C 44=1+4+6+4+1=16种情况
上面两种计算都是计算排列种类,并非是行数,行数由具体被分组的该列的值所确定的,这个虽然可以计算,但是比较麻烦也无意义,所以我的理解cube和rollup其实相当于对group 的多列字段进行排列,然后将每种排列进行展示或者进行聚合计算。