您现在的位置是:网站首页> 编程资料编程资料
Oracle分组函数之ROLLUP的基本用法_oracle_
2023-05-27
480人已围观
简介 Oracle分组函数之ROLLUP的基本用法_oracle_
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 11g 数据库的部署的图文教程_oracle_
- Oracle数据库创建存储过程的示例详解_oracle_
- 通过PLSQL Developer创建Database link,DBMS_Job,Procedure,实现Oracle跨库传输数据的方法(推荐)_oracle_
- Maven中央仓库正式成为Oracle官方JDBC驱动程序组件分发中心(推荐)_oracle_
- Oracle数据库常用命令整理(实用方法)_oracle_
- Oracle利用errorstack追踪tomcat报错ORA-00903 无效表名的问题_oracle_
- Oracle按身份证号得到省市、性别、年龄的示例代码_oracle_
- Windows10安装Oracle19c数据库详细记录(图文详解)_oracle_
- Oracle dbf文件移动的方法_oracle_
- Oracle SQLPlus导出数据到csv文件的方法_oracle_
