SQL面试题挑战12:计算部门的平均工资

目录

  • 问题:
  • SQL解答:

问题:

现在要计算每个部门的平均工资(工资和/员工数),但是要去掉部门的最高工资和最低工资(如果一个部门最高或最低工资有并列的,去掉一个最高的和一个最低的)后,计算部门的平均工资。


	 101 	,"研发部" 	,50000 		
     102 	,"研发部" 	,50000 		
     103 	,"研发部" 	,10000 	
     104 	,"研发部" 	,20000 	
     105 	,"研发部" 	,30000 	
     106 	,"市场部" 	,20000 	
     107 	,"市场部" 	,30000 	
     108 	,"产品部" 	,20000 	
     109 	,"产品部" 	,30000 	
     110 	,"产品部" 	,25000 
     111    ,"市场部"	,14000
     112    ,"市场部"	,8000
     113	,"产品部"	,20000 

SQL解答:

使用开窗函数找出该部门的最高工资和最低工资,并按最高到最低和最低到最高分别给排名,最后排除掉满足工资要求且排名在最前面的员工即可。

with temp as
(
    select 101 as user_id,"研发部" as dept,50000 as salary
    union all
    select 102 as user_id,"研发部" as dept,50000 as salary
    union all
    select 103 as user_id,"研发部" as dept,10000 as salary
    union all
    select 104 as user_id,"研发部" as dept,20000 as salary
    union all
    select 105 as user_id,"研发部" as dept,30000 as salary
    union all
    select 106 as user_id,"市场部" as dept,20000 as salary
    union all
    select 107 as user_id,"市场部" as dept,30000 as salary
    union all
    select 108 as user_id,"产品部" as dept,20000 as salary
    union all
    select 109 as user_id,"产品部" as dept,30000 as salary
    union all
    select 110 as user_id,"产品部" as dept,25000 as salary
    union all 
    select 111 as user_id,"市场部" as dept,14000 as salary
    union all
    select 112 as user_id,"市场部" as dept,8000 as salary
    union all
    select 113 as user_id,"产品部" as dept,20000 as salary
)
select
dept
,dept_total_salary
,dept_employee_cnt
,round(dept_total_salary/dept_employee_cnt,2) as dept_avg_salary
from
(
    select
    dept
    ,sum(if((salary=min_salary and min_salary_rn=1) or (salary=max_salary and max_salary_rn=1),0,salary)) as dept_total_salary --去掉一个最高工资和一个最低工资后剩下的部门总工资
    ,sum(if((salary=min_salary and min_salary_rn=1) or (salary=max_salary and max_salary_rn=1),0,1)) as dept_employee_cnt  --去掉一个最高分和一个最低分后的剩余人数
    from
    (
        select
        user_id
        ,dept
        ,salary
        ,min(salary) over(partition by dept) as min_salary --部门的最高工资
        ,max(salary) over(partition by dept) as max_salary --部门的最低工资
        ,row_number() over(partition by dept order by salary desc) as max_salary_rn  --为了使用编号去掉其中一个最高分
        ,row_number() over(partition by dept order by salary) as min_salary_rn  --为了使用编号去掉其中一个最低分
        from temp 
    )t1
    group by dept
)t1
;

----结果为:
dept		dept_total_salary		dept_employee_cnt		dept_avg_salary	
产品部			45000						2					22500.0
市场部          34000                       2                   17000.0
研发部          100000                      3                   33333.33

你可能感兴趣的:(SQL面试题,sql,面试)