分析函數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