如何为多个子查询赋予特定值?

时间:2019-06-24 09:35:59

标签: mysql

我必须进行查询,其中需要找到部门名称以及男女平均工资的最高比例。

我完成了查询,该查询给出了确切的比率,但是我必须将硬编码的值放在dept_no列中,并且我想对其进行修改以表明它可以从部门表的所有位置获取值。

select dept_name,
    ((select  max(avg_val) from 
        (select avg(s.salary)as avg_val 
         from salaries s, employees e, dept_emp dp 
         where  e.emp_no = s.emp_no 
            and dp.dept_no = 'd005'
            and e.gender = 'F'
            and e.emp_no = dp.emp_no
        group by s.emp_no,e.emp_no,dp.emp_no,dp.dept_no
        ) tmp
    )  
 /
    (select  max(avg_val) 
     from ( select avg(s.salary) as avg_val 
            from  salaries s, employees e, dept_emp dp 
            where e.emp_no = s.emp_no 
            and dp.dept_no = 'd005'
            and e.gender = 'M'
            and e.emp_no = dp.emp_no
            group by s.emp_no,e.emp_no,dp.emp_no,dp.dept_no
          ) tmp
    )
) as Avgerage 
from departments 
where dept_no = 'd005';

当前结果:

dept_name      Average
'Development', '0.96394531'

必填结果:

all department name and their average ratio.

1 个答案:

答案 0 :(得分:0)

尝试以下SQL:

select dept_no, dept_name, B.sal / C.sal as Avgerage
from departments A
join (select  dp.dept_no, max(avg_val) as sal from
        (select dp.dept_no, avg(s.salary)as avg_val
         from salaries s, employees e, dept_emp dp
         where  e.emp_no = s.emp_no
            and e.gender = 'F'
            and e.emp_no = dp.emp_no
        group by s.emp_no,e.emp_no,dp.emp_no,dp.dept_no
        ) tmp
  GROUP BY tmp.dept_no
    ) B ON A.dept_no = B.dept_no
join (select  dp.dept_no, max(avg_val) as sal from
          ( select dp.dept_no, avg(s.salary) as avg_val
            from  salaries s, employees e, dept_emp dp
            where e.emp_no = s.emp_no
            and e.gender = 'M'
            and e.emp_no = dp.emp_no
            group by s.emp_no,e.emp_no,dp.emp_no,dp.dept_no
          ) tmp
      GROUP BY tmp.dept_no
    ) C ON A.dept_no = B.dept_no
GROUP BY dept_no,dept_name;

我没有SQL DDL,因此可能需要进行一些修改,但是主要思想是按部门分别对男性和女性的所有薪水值进行分组,然后在主查询中计算平均值,并按部门编号。

希望有帮助!