[SQL] rollup & cube 分組函式用法及一例

guocun09發表於2017-11-07

rollup

First, it calculates the standard aggregate values specified in the GROUP BY clause. Then, it creates progressively higher-level subtotals, moving from right to left through the list of grouping columns. Finally, it creates a grand total.

n+1superaggregate combinations

select grouping(owner),grouping(object_type),owner,object_type,count(*) from gc.test

group by rollup(owner,object_type)

order by owner;

先對owner,object_type分組,再對owner分組(也就是小計),最後再合計,

grouping可看到小計級別。 

如果rollup(a,b,c),那就先對a,b,c分組,再對a,b分組,再對a分組,最後再合計。

 

cube

cube(a,b,c),順序先a,b,c 再a,b 再a,c a b,c b c 再合計

It produces 2n次方 possible superaggregate combinations, if the n columns and expressions are specified in the GROUP BY clause.

注:The HAVING,GROUP BY clause conditions can’t use aliases for the columns.

        But ORDER BY clause can use aliases.



SQL一例,按分鐘先小計,再按小時合計:
select grouping(TO_CHAR(CREATED,'yyyy-mm-dd hh24')),grouping(TO_CHAR(CREATED,'yyyy-mm-dd hh24:mi')),
TO_CHAR(CREATED,'yyyy-mm-dd hh24'),TO_CHAR(CREATED,'yyyy-mm-dd hh24:mi'),count(1) from dba_objects
group by rollup(TO_CHAR(CREATED,'yyyy-mm-dd hh24'),TO_CHAR(CREATED,'yyyy-mm-dd hh24:mi'))
order by TO_CHAR(CREATED,'yyyy-mm-dd hh24')

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/25583515/viewspace-2146923/,如需轉載,請註明出處,否則將追究法律責任。

相關文章