Oracle分组函数之ROLLUP的基本用法
数据库  /  管理员 发布于 6年前   201
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.dnameunion allselect 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.jobunion all//各部门的工资之和select a.dname, null, sum(b.sal) from scott.dept a, scott.emp b where a.deptno = b.deptno group by a.dnameunion 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)、()
....
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对AIDI的支持。
122 在
学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..123 在
Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..原梓番博客 在
在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..博主 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..1111 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
Copyright·© 2019 侯体宗版权所有·
粤ICP备20027696号