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

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

http://www.nowcoder.com/practice/95078e5e1fba4438b85d9f11240bc591

SQL 第54题

解法一
select
avg(salary)
from salaries
where salary not in (
select
min(salary)
from salaries
where to_date = '9999-01-01'
)
and salary not in (
select
max(salary)
from salaries
where to_date = '9999-01-01'
)
and to_date = '9999-01-01'
#where不能用聚合函数 因此用select 排除最大值和最小值
简单粗暴

解法二 窗口函数
select
avg(salary)
from (
select
*
,row_number() over(order by salary) r1
,row_number() over(order by salary desc) r2
from salaries
where to_date = '9999-01-01'
) a
where a.r1 <>1
and a.r2 <> 1
#把最大值和最小值去掉
解法三 把最大和最小去掉

select
avg(salary)
from (
select
salary
,max(salary) over() s1
,min(salary) over() s2
from salaries
where to_date = "9999-01-01"
) a
where a.salary < a.s1
and a.salary > a.s2

值得注意的点:
一、解法三必须使用窗口函数,因为直接使用max或者min只输出一个观测值,除非使用join将所有观测和max与min连接起来,那样会很麻烦,而窗口函数则直接输出全部值。
二、注意算法运行的顺序,where后面不能使用聚合函数,where在select前运行。
三、“Having”是一个过滤声明,所谓过滤是在查询数据库的结果返回之后进行过滤,即在结果返回之后起作用,并且having后面可以使用“聚合函数”。

全部评论
方法2和方法3真的绝
2 回复 分享
发布于 2021-12-29 21:12
第二种解法如果出现两个或以上相同的最高工资或者最低工资的话,那么a.ri<>1,也有可能是最高的工资,题目没说排除几个最高的
1 回复 分享
发布于 2022-08-17 02:20 广东
厉害。第三种我还看不太懂哈哈哈
1 回复 分享
发布于 2022-03-29 05:07
请问方法二的a.ri<>1,<>是不等于的意思吗,为什么不写>1呢,排序后不就是不取第一个数
点赞 回复 分享
发布于 2024-11-04 15:57 四川
to_date = '9999-01-01' 为当前员工,即在职员工
点赞 回复 分享
发布于 2024-07-20 12:43 江苏
方法一,最后and to_date = '9999-01-01'是啥思路啊?题目要求看不太懂啊,是要去掉所有date = '9999-01-01'的员工吗?
点赞 回复 分享
发布于 2023-08-05 10:32 山东
绝绝绝,值得注意的点也写的很好,直接解决了菜鸟(我自己)的问题
点赞 回复 分享
发布于 2022-03-01 15:45
方法二为什么不等于不能写在里面?
点赞 回复 分享
发布于 2022-01-19 20:13

相关推荐

Cherrycola01:0实习 0项目 约等于啥也没有啊 哥们儿这简历认真的吗
点赞 评论 收藏
分享
评论
36
9
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务