select*, rank() over (partitionby 部门编号 order by 薪水 desc) as rank_1,rank() over (partitionby 部门编号 order by 薪水) as rank_2from 薪水表where rank_1 >1and rank_2 >1;
但是这样运行会出错,因为按照 sql 的运行顺序,会先运行 from 和 where 子句,最后才运行 select 子句。
select*from (select*,rank() over (partitionby 部门编号 order by 薪水 desc) as rank_1,rank() over (partitionby 部门编号 order by 薪水) as rank_2from 薪水表 ) as awhere a.rank_1 >1and 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 (partitionby 部门编号 order by 薪水 desc) as rank_1,rank() over (partitionby 部门编号 order by 薪水) as rank_2from 薪水表 ) as awhere a.rank_1 >1and a.rank_2 >1group by a.部门编号;
selectformat(avg(a.成绩),2) as 平均成绩from (select*,rank() over (order by 成绩 desc) as rank_1,rank() over (order by 成绩) as rank_2from 成绩表 ) as awhere a.rank_1 >1and a.rank_2 >1;