Oracle分组函数之ROLLUP的基本用法

所属分类: 数据库 / oracle 阅读数: 1335
收藏 0 赞 0 分享

rollup函数

本博客简单介绍一下oracle分组函数之rollup的用法,rollup函数常用于分组统计,也是属于oracle分析函数的一种

环境准备

create table dept as select * from scott.dept;
create table emp as select * from scott.emp;

业务场景:求各部门的工资总和及其所有部门的工资总和

这里可以用union来做,先按部门统计工资之和,然后在统计全部部门的工资之和

select a.dname, sum(b.sal)
 from scott.dept a, scott.emp b
 where a.deptno = b.deptno
 group by a.dname
union all
select null, sum(b.sal)
 from scott.dept a, scott.emp b
 where a.deptno = b.deptno;

上面是用union来做,然后用rollup来做,语法更简单,而且性能更好

select a.dname, sum(b.sal)
 from scott.dept a, scott.emp b
 where a.deptno = b.deptno
 group by rollup(a.dname);

业务场景:基于上面的统计,再加需求,现在要看看每个部门岗位对应的工资之和

select a.dname, b.job, sum(b.sal)
 from scott.dept a, scott.emp b
 where a.deptno = b.deptno
 group by a.dname, b.job
union all//各部门的工资之和
select a.dname, null, sum(b.sal)
 from scott.dept a, scott.emp b
 where a.deptno = b.deptno
 group by a.dname
union all//所有部门工资之和
select null, null, sum(b.sal)
 from scott.dept a, scott.emp b
 where a.deptno = b.deptno;

用rollup实现,语法更简单

select a.dname, b.job, sum(b.sal)
 from scott.dept a, scott.emp b
 where a.deptno = b.deptno
 group by rollup(a.dname, b.job);

假如再加个时间统计的,可以用下面sql:

select to_char(b.hiredate, 'yyyy') hiredate, a.dname, b.job, sum(b.sal)
 from scott.dept a, scott.emp b
 where a.deptno = b.deptno
 group by rollup(to_char(b.hiredate, 'yyyy'), a.dname, b.job);

cube函数

select a.dname, b.job, sum(b.sal)
 from scott.dept a, scott.emp b
 where a.deptno = b.deptno
 group by cube(a.dname, b.job);

cube

函数是维度更细的统计,语法和rollup类似

假设有n个维度,那么rollup会有n个聚合,cube会有2n个聚合

rollup统计列

rollup(a,b) 统计列包含:(a,b)、(a)、()

rollup(a,b,c) 统计列包含:(a,b,c)、(a,b)、(a)、()

....

cube统计列

cube(a,b) 统计列包含:(a,b)、(a)、(b)、()

cube(a,b,c) 统计列包含:(a,b,c)、(a,b)、(a,c)、(b,c)、(a)、(b)、(c)、()

....

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对脚本之家的支持。

更多精彩内容其他人还在看

Oracle 子程序参数模式,IN,OUT,NOCOPY

Oracle 子程序参数模式主要有IN,OUT,NOCOPY,IN和OUT可以组合,OUT和NOCOPY也可以组合使用.
收藏 0 赞 0 分享

Oracle 存储过程加密方法

Oracle 存储过程加密方法,需要的朋友可以参考下。
收藏 0 赞 0 分享

oracle 多个字符替换实现

CSDN上的一个网友,需要一个sql语句的解决方案需求是这样的求写oracle多个字符替换(有测试数据)
收藏 0 赞 0 分享

Oracle 存储过程教程

一个简单的oracle分页存储过程的实现和调用。在看了众多的分页存储过程以后发现都是针对sqlserver的,而没有oracle的,因此想写一个关于oracle的存储过程,因为我用到的数据库是oracle。
收藏 0 赞 0 分享

oracle 更改数据库名的方法

这两天一朋友问如何更改数据库名,于是做个测试,简单记录下,以便说明问题。
收藏 0 赞 0 分享

Oracle 分析函数RANK(),ROW_NUMBER(),LAG()等的使用方法

Oracle分析函数RANK(),ROW_NUMBER(),LAG()等的使用方法,需要的朋友可以参考下。
收藏 0 赞 0 分享

Oracle字符集修改查看方法

Oracle字符集修改查看方法,需要的朋友可以参考下。
收藏 0 赞 0 分享

一些实用的sql语句

一些实用的sql,需要的朋友可以参考下。
收藏 0 赞 0 分享

Oracle中sys和system的区别小结

SYS用户具有DBA权限,并且拥有SYS模式,只能通过SYSDBA登陆数据库。是Oracle数据库中权限最高的帐号 SYSTEM具有DBA权限。但没有SYSDBA权限。平常一般用该帐号管理数据库就可以了。
收藏 0 赞 0 分享

oracle 存储过程和触发器复制数据

oracle 存储过程和触发器复制数据的代码,需要的朋友可以参考下。
收藏 0 赞 0 分享
查看更多