简体   繁体   中英

How to divide by the result of another query

This is a separate question based on a previous post:

[Link] How to calculate Grand Totals when using OVER (partition by ...) using Oracle SQL

I am using the following Oracle SQL query:

SELECT JOB_GROUP,
   SUM(PEOPLE) AS CURRENT_PEOPLE
   SUM(PEOPLE) / '100' AS RATIO
FROM MY_VIEW
WHERE MONTH = '01-DEC-2013'
GROUP BY ROLLUP (OB_GROUP)
ORDER BY RATIO DESC;

This query gives me an output like this..

JOB_GROUP    CURRENT_PEOPLE    RATIO
WORKER1     100                1.0
WORKER2     30                 .3
WORKER3     40                 .4
WORKER4     25                 .25
WORKER5     30                 .30
(NULL)      225                2.25

I need to be able to divide the sum of all of the ratios into the sum of the ratios where job_group = 'WORKER1', WORKER2, WORKER4. For Example, we can have 5 different job_groups, but I only need the sum of the ratio for 1, 2 and 4. I suspect this is some type of subquery, but have not been able to get the right result yet.

The equation would look like sum(ratios) / sum(ratio) where worker, 1,2,4. 2.25 / (1.0 + .3 + .25) = .80

Thanks for any help you can provide,

The following uses an analytic function to get the number of worker1s:

select JOB_GROUP, CURRENT_PEOPLE,
       CURRENT_PEOPLE / sum(job_group = 'WORKER1' then CURRENT_PEOPLE end) over () as Ratio
from (SELECT JOB_GROUP,
             SUM(PEOPLE) AS CURRENT_PEOPLE
      FROM my_view
      WHERE MONTH = '01-DEC-2013'
      GROUP BY ROLLUP (JOB_GROUP)
     ) t
ORDER BY RATIO DESC;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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