Difference rollup function and the cube function?

    有的小伙伴会发现在数据统计报表的时候会经常在最后对列进行一个汇总,那么在oracle中是那些函数来实现汇总的呢?今天就来讲一下rollup函数和cube函数的区分。
首先,创建一张表tmp1,数据如下:

Difference rollup function and the cube function?
So, we look at the cube data is aggregated out what's right?
select t_class, t_address, (t_number) t_number from tmp1 group by cube (t_class, t_address);
Difference rollup function and the cube function?
some may have found a small partner, the cube function summary data equivalent to the data summarized all the possibilities out. Yes, in fact this sql statement is equivalent to the union all of the following statements:
the SELECT null, null, SUM (t_number) t_number from TMP1
union all
the SELECT null, t_address, SUM (t_number) t_number from TMP1 Group by t_address
union all
the SELECT T_CLASS, null, SUM (t_number) t_number from Group TMP1 T_CLASS by
Union All
SELECT T_CLASS, t_address, SUM (t_number) t_number from Group TMP1 by T_CLASS, t_address;

Well, now we look at the summary rollup data out what is right?
select t_class, t_address, (t_number) t_number from tmp1 group by rollup (t_class, t_address);
Difference rollup function and the cube function?
some may have found a small partner, the function summary rollup data can also be used to achieve union all statements:
the SELECT null, null, SUM ( t_number) t_number TMP1 from
Union All
SELECT T_CLASS, null, SUM (t_number) t_number from Group TMP1 T_CLASS by
Union All
SELECT T_CLASS, t_address, SUM (t_number) t_number from Group TMP1 by T_CLASS, t_address;

    **总结:**
    如果使用group by rollup(A,B,C),首先会对(A、B、C)进行GROUP BY,然后对(A、B)进行GROUP BY,然后是(A)进行GROUP BY,最后对全表进行GROUP BY操作。roll up的意思是“卷起”,这也可以帮助我们理解group by rollup就是对选择的列从右到左以一次少一列的方式进行grouping直到所有列都去掉后的grouping(也就是全表grouping),对于n个参数的rollup,有n+1次的grouping。

cube的意思是立方,对cube的每个参数,都可以理解为取值为参与grouping和不参与grouping两个值的一个维度,然后所有维度取值组合的集合就是grouping的集合,对于n个参数的cube,有2^n次的grouping。如果使用group by cube(A,B,C),,则首先会对(A、B、C)进行GROUP BY,然后依次是(A、B),(A、C),(A),(B、C),(B),(C),最后对全表进行GROUP BY操作,一共是2^3=8次grouping。

另外,当实际表中也存在null值时,如何区分cube和rollup运算符所生成的null值呢?这时我们可以用grouping函数来区分,这里我们就举一个简单的例子来区分t_class列的null值,sql如下:
select t_class,t_address,(t_number) t_number,grouping(t_class) from tmp1

group by rollup (t_class, t_address) ;
Difference rollup function and the cube function?
From the figure can be seen grouping (t_class) column two digits 0 and 1, where 1 represents a null value rollup caused by the operator, the fact that the remaining value is null null data . In fact grouping is a function of the polymerization, it produces an additional column, when a cube or rollup operator adds rows, additional columns is 1; and when the row is not generated by the added cube or rollup, additional column values 0.

I hope we can help!

Guess you like

Origin blog.51cto.com/12777507/2402657