ITPub博客

首页 > 数据库 > Oracle > [SQL] rollup & cube 分组函数用法及一例

[SQL] rollup & cube 分组函数用法及一例

原创 Oracle 作者:guocun09 时间:2017-11-07 11:10:02 0 删除 编辑

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+1次superaggregate 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 2的n次方 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博客 ” ,链接:https://blog.itpub.net/25583515/viewspace-2146923/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论
DBA,掌握Oracle,SQLServer,MySQL,hadoop,casscandra等数据库。喜爱深入研究数据库技术原理,擅长管理和优化工作。

注册时间:2011-10-02

  • 博文量
    177
  • 访问量
    686671