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

问题:

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


	 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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值