18 Star 92 Fork 52

柯基与佩奇 / 数据库SQL实战

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
54.查找排除当前最大最小salary之后的员工的平均工资avg_salary.md 1.52 KB
一键复制 编辑 原始数据 按行查看 历史

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

题目描述

查找排除当前最大、最小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')

题解

使用min和max函数获得最大值最小值,而后用not in将最大值最小值记录去除,求平均

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
SQL
1
https://gitee.com/wp950820/database-sql-combat.git
git@gitee.com:wp950820/database-sql-combat.git
wp950820
database-sql-combat
数据库SQL实战
master

搜索帮助