有员工薪资表t3_salary,包含员工ID(emp_id),部门ID(depart_id),薪水(salary),请计算去除最高最低薪资后的平均薪水;(每个部门员工数不少于3人)
CREATE TABLE t3_salary (
emp_id bigint,
depart_id bigint,
salary decimal(16,2)
);
insert into t3_salary (emp_id,depart_id,salary)
values
(1001,1,5000.00),
(1002,1,10000.00),
(1003,1,20000.00),
(1004,1,30000.00),
(1005,1,6000.00),
(1006,1,10000.00),
(1007,1,11000.00),
(1008,2,3000.00),
(1009,2,7000.00),
(1010,2,9000.00),
(1011,2,30000.00);
ROW_NUMBER()
是一个窗口函数,它为结果集中的每一行分配一个唯一的连续整数,通常用于数据的排序和分区。这个函数在处理数据分页、排名或者在分析查询中生成唯一的行号时非常有用。
1.分别按照正序和倒序进行开窗,得到部门最高最低薪资记录
select emp_id,
depart_id,
salary,
row_number() over (partition by depart_id order by salary asc) as asc_order,
row_number() over (partition by depart_id order by salary desc) as desc_order
from t3_salary;
2.去掉最高最低薪资
select emp_id,
depart_id,
salary,
asc_order,
desc_order
from (select emp_id,
depart_id,
salary,
row_number() over (partition by depart_id order by salary asc) as asc_order,
row_number() over (partition by depart_id order by salary desc) as desc_order
from t3_salary) t
where asc_order > 1
and desc_order > 1
3.查询部门平均薪水
select depart_id,
avg(salary) as avg_salary
from (select emp_id,
depart_id,
salary,
row_number() over (partition by depart_id order by salary asc) as asc_order,
row_number() over (partition by depart_id order by salary desc) as desc_order
from t3_salary) t
where asc_order > 1
and desc_order > 1
group by depart_id