select *,
rank() over (partition by 部门编号 order by 薪水 desc) as rank_1,
rank() over (partition by 部门编号 order by 薪水) as rank_2
from 薪水表
where rank_1 >1 and rank_2 >1;
但是这样运行会出错,因为按照 sql 的运行顺序,会先运行 from 和 where 子句,最后才运行 select 子句。
select *
from (
select *,
rank() over (partition by 部门编号 order by 薪水 desc) as rank_1,
rank() over (partition by 部门编号 order by 薪水) as rank_2
from 薪水表
) as a
where a.rank_1 >1 and a.rank_2 >1;
查询结果如下,此时已经是每个部门去掉最高、最低薪水后的结果了。
3. 查询每个部门除去最高、最低薪水的平均薪水
看到 “每个” 这样的问题,要想到用分组(group by),平均薪水使用 avg 函数。
另外,题目还要求薪水保留整数。保留整数即保留 0 位小数,可以用 format 函数:
format(N,D)
N是要格式化的数字
D是要舍入的小数位数。
select a.部门编号,format(avg(a.薪水),0) as 平均薪水
from
(
select *,
rank() over (partition by 部门编号 order by 薪水 desc) as rank_1,
rank() over (partition by 部门编号 order by 薪水) as rank_2
from 薪水表
) as a
where a.rank_1 >1 and a.rank_2 >1
group by a.部门编号;
select format(avg(a.成绩),2) as 平均成绩
from
(
select *,
rank() over (order by 成绩 desc) as rank_1,
rank() over (order by 成绩) as rank_2
from 成绩表
) as a
where a.rank_1 >1 and a.rank_2 >1;