这道题目要求我们计算在职员工的平均薪水,但需要排除当前在职员工中最高和最低的薪水。我们要做的事情如下:

1. 确定总体问题

我们需要从薪水表中提取数据,提取在职员工(to_date = '9999-01-01')的薪水,通过子查询来排除最高和最低薪水,然后计算剩余员工的平均薪水。

2. 分析关键问题

  • 筛选在职员工:通过to_date = '9999-01-01'条件筛选出在职员工。
  • 排除最高和最低薪水:使用子查询找出最高和最低的薪水,并在主查询中排除这些薪水。
  • 计算平均薪水:对剩余的薪水计算平均值。

3. 解决每个关键问题的代码及讲解

步骤1:筛选在职员工

我们通过to_date = '9999-01-01'条件筛选出在职员工:

where
    to_date = '9999-01-01'
步骤2:排除最高和最低薪水

我们使用子查询找出最高和最低的薪水,并在主查询中排除这些薪水:

salary not in (
    select max(salary) from salaries where to_date = '9999-01-01'
) and salary not in (
    select min(salary) from salaries where to_date = '9999-01-01'
)
  • select max(salary) from salaries where to_date = '9999-01-01':找出在职员工的最高薪水。
  • select min(salary) from salaries where to_date = '9999-01-01':找出在职员工的最低薪水。
  • salary not in...:排除最高薪水和最低薪水。
步骤3:计算平均薪水

我们对剩余的薪水计算平均值:

select
    avg(salary) as avg_salary
from
    salaries
  • avg(salary):计算薪水的平均值

完整代码

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