## xuthus / 数据库SQL实战SQLMIT

Explore and code with more than 6 million developers，Free private repositories ！：）
54.查找排除当前最大最小salary之后的员工的平均工资avg_salary.md 1.23 KB
xuthus authored 2019-08-12 23:23 . add:all

# 查找排除当前最大、最小salary之后的员工的平均工资avg_salary

## 题目描述

```CREATE TABLE `salaries` ( `emp_no` int(11) NOT NULL,
`salary` int(11) NOT NULL,
`from_date` date NOT NULL,
`to_date` date NOT NULL,
PRIMARY KEY (`emp_no`,`from_date`));```

## 答案

`select avg(salary) avg_salary from salaries s where to_date = '9999-01-01' and salary not in (select min(salary) from salaries where s.to_date = '9999-01-01') and salary not in (select max(salary) from salaries where s.to_date = '9999-01-01')`

## 题解

1、获得salary最大值maxRecord最小值minRecord记录(逻辑上需要按照当前时间的salary进行筛选)

```select max(salary) from salaries where s.to_date = '9999-01-01')
select min(salary) from salaries where s.to_date = '9999-01-01')```

2、去除最大值最小值记录 t1

`select * from salaries where to_data = '9999-01-01' and salary not in maxRecord and salary not in minRecord`

3、对上面的临时表求平均值即可

`select avg(salary) from t1`