繁体   English   中英

如何计算列中的百分比?

[英]How to calculate percentage in column?

我有一项任务是计算部门中的最低工资,并从总工资中计算出多少百分比。 我也只能使用一个选择语句, 可能我需要使用窗口函数。

这就是我开始的方式:

     SELECT distinct department_id,
     min(salary) over(partition by department_id) as min_sal
     FROM employees;

但是,如果我使用RATIO_TO_REPORT函数,它将显示所有表,而不是按department_id分组。

听起来好像

select min(salary) as min_salary, round( min(salary)/sum(salary) * 100 , 1 ) as percent
from   employees
group by department_id
;

如果您还需要每个部门中薪水最低的员工的姓名(假设总是只有一个),则添加

    , min(empl_name) keep (dense_rank first order by salary) as min_sal_empl_name

SELECT语句。 如果可以以最低的薪水建立关系,并且您需要所有员工,请这样说-在这种情况下,您可能需要您所猜测的分析功能。 就像是:

select empl_name, salary, round(salary/tot_sal*100, 1) as percent
from   ( select empl_name, salary, 
                sum(salary) over (partition by department_id)            as tot_sal,
                rank() over (partition by department_id order by salary) as rn
         from   employees 
       )
where  rn = 1
;  

补充 :OP表示他们毕竟需要薪水(占所有部门的薪水)占总薪水的百分比。 这可以通过将ratio_to_report()与空的开窗条件(没有“被任何东西划分”)与按部门划分的rank()起来以在每个部门中获取最低工资来完成。

如果你不喜欢over ()在窗口第ratio_to_report()它也可以被写成over (partition by null) ,使用户能够无比清晰的划分没有打算或需要。

该解决方案使用SCOTT架构中的EMP表进行测试,因为原始帖子不包含示例数据。

select deptno, empno, ename, sal, percent
from   (
         select empno, ename, sal, deptno,
                round(100 * ratio_to_report(sal) over (), 1)   as percent,
                rank() over (partition by deptno order by sal) as rn
         from   scott.emp
       )
where  rn = 1
;


DEPTNO  EMPNO  ENAME    SAL  PERCENT
------  -----  ------  ----  -------
10       7934  MILLER  1300      4.5
20       7369  SMITH    800      2.8
30       7900  JAMES    950      3.3

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM