数据库 
首页 > 数据库 > 浏览文章

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

(编辑:jimmy 日期: 2024/9/21 浏览:3 次 )

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);

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

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

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);

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

假如再加个时间统计的,可以用下面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);

Oracle分组函数之ROLLUP的基本用法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游标的简易用法
下一篇:ORACLE中如何找到未提交事务的SQL语句详解
一句话新闻
微软与英特尔等合作伙伴联合定义“AI PC”:键盘需配有Copilot物理按键
几个月来,英特尔、微软、AMD和其它厂商都在共同推动“AI PC”的想法,朝着更多的AI功能迈进。在近日,英特尔在台北举行的开发者活动中,也宣布了关于AI PC加速计划、新的PC开发者计划和独立硬件供应商计划。
在此次发布会上,英特尔还发布了全新的全新的酷睿Ultra Meteor Lake NUC开发套件,以及联合微软等合作伙伴联合定义“AI PC”的定义标准。
友情链接:杰晶网络 DDR爱好者之家 南强小屋 黑松山资源网 白云城资源网 SiteMap