是否有任何oracle函数可以帮助我计算接受某些条件的行的百分比
示例表:
WorkerId Salary DepartmentId
10001 2000.00 1
10002 2500.00 2
10004 3000.00 1
10005 3500.00 1
我想知道每个部门工资超过2100.00的工人百分比
答案 0 :(得分:3)
您可以使用RATIO_TO_REPORT
:
SELECT departmentID, 100 * SUM(rr) AS total_percentage
FROM (SELECT t.*, RATIO_TO_REPORT(1) OVER (PARTITION BY DepartmentId) AS rr
FROM your_tab t) s
WHERE salary > 2100
GROUP BY departmentId;
<强> DBFiddle Demo 强>
输出:
DEPARTMENTID TOTAL_PERCENTAGE
1 66.66
2 100
答案 1 :(得分:0)
尝试使用两个GROUP BY
和JOIN
SELECT yt.DepartmentId, t.hs/count(*) * 100
FROM your_tab yt
JOIN
(
SELECT DepartmentId, count(*) as hs
FROM your_tab
WHERE salary > 2100
GROUP BY DepartmentId
) t ON yt.DepartmentId = t.DepartmentId
GROUP BY yt.DepartmentId, t.hs
答案 2 :(得分:0)
您无需使用分析函数即可完成此操作,如下所示:
WITH sample_data AS (SELECT 10001 workerid, 2000 salary, 1 departmentid FROM dual UNION ALL
SELECT 10002 workerid, 2500 salary, 2 departmentid FROM dual UNION ALL
SELECT 10004 workerid, 3000 salary, 1 departmentid FROM dual UNION ALL
SELECT 10005 workerid, 3500 salary, 1 departmentid FROM dual)
-- end of subquery mimicking a table with your data in it.
-- see SQL query below:
SELECT departmentid,
100*(COUNT(CASE WHEN salary > 2100 THEN 1 END)/COUNT(*)) pct_earning_gt_2100
FROM sample_data
GROUP BY departmentid;
DEPARTMENTID PCT_EARNING_GT_2100
------------ -------------------
1 66.6666666666667
2 100
这使用条件计数(请记住,大多数聚合函数都会忽略空值)来确定在除以每个部门的总行数之前满足条件的行数。
这应该比涉及ratio_to_report分析函数的解决方案更高效,因为在执行group by之前不需要执行额外的步骤,但是您应该测试两个解决方案以找出哪个实际上更好数据