分析函数Ratio_to_report分解!

分析函数Ratio_to_report( ) over()使用说明

表中需要计算单项占比:比如单项在部门占比多少,单项在公司占比多少。特别是在财务单项计算,部门个人薪水计算上。

Ratio_to_report() 括号中就是分子,over() 括号中就是分母,分母缺省就是整个占比。

Ratio_to_report 一般结合partition by 使用。

(一)

举例子说明:

emp,dept,两表关联列为 deptno

create,insert into 步骤省略。

SQL> select * from emp;

EMPNO DEPTNO SALARY

--------------------------------------- --------------------------------------- ----------

100 2 55

101 1 50

102 2 60

SQL> select * from dept;

DEPTNO SUM_OF_SALARY

--------------------------------------- -------------

1 50

2 115

(二)脚本:

sum(salary) 是对每个部门deptno求和,partition by 是对部门分区,分组。

pct_dept 是每个员工salary对部门的占比;

pct_overall 是每个员工salary对整个公司的占比;

select empno,
deptno,
salary,
sum(salary) over (partition by deptno order by deptno) sum_deptno_salary,
ROUND(
100*ratio_to_report(salary)
over (partition by deptno),
1) pct_dept,
ROUND(
100*ratio_to_report(salary)
over(),
1) pct_overall
from emp
order by empno,deptno

查询结果:

EMPNO DEPTNO SALARY SUM_DEPTNO_SALARY PCT_DEPT PCT_OVERALL

--------------------------------------- --------------------------------------- ---------- ----------------- ----------

100 2 55 115 47.8 33.3

101 1 50 50 100 30.3

102 2 60 115 52.2 36.4

(三)

ratio_to_report分析函数是oracle 8i以后才有的。如果DATABASE 不支持。可以改写:

select emp.empno,
emp.deptno,
emp.salary,
emp2.a,
round(
100*emp.salary/emp2.a,1) pct_dept_zb,
round(
100*emp.salary/emp3.b,1) pct_overall_zb
from emp,
(select deptno,sum(salary) a from emp
group by deptno
order by deptno,a
) emp2,
(select sum(salary) b from emp
order by deptno
) emp3

where emp.deptno=emp2.deptno

group by emp.empno,
emp.deptno,
emp.salary,
emp2.a,
round(
100*emp.salary/emp2.a,1),
round(
100*emp.salary/emp3.b,1)
order by emp.empno,emp.deptno
结果验证:

EMPNO DEPTNO SALARY A PCT_DEPT_ZB PCT_OVERALL_ZB

------- --------------------------------------- ---------- ------

100 2 55 115 47.8 33.3

101 1 50 50 100 30.3

102 2 60 115 52.2 36.4

请oracle朋友加入:149196034

[@more@]

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/22934571/viewspace-1043945/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/22934571/viewspace-1043945/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值