[英]Finding the second highest salary by subqueries
I have two tables employees and departments. 我有两个表的员工和部门。
Employees table has name, salary, department_id. 员工表具有名称,工资,部门编号。 Departments table has department_id, department_name
部门表具有部门编号,部门名称
I have to display the employee with the second highest(Literally the only one employee who has the second highest salary among every employee in the employees table) and his department_name using subqueries 我必须使用子查询显示第二高的雇员(实际上是雇员表中每个雇员中唯一拥有第二高工资的雇员)和他的department_name
select
max(e.salary),
d.department_name
from oehr_employees e
join oehr_departments d on(e.department_id = d.department_id)
where e.salary not in(
select max(salary) from oehr_employees
)
group by department_name
tried to do this one, but it shows only the second highest salary of each department. 试图做到这一点,但它仅显示每个部门的第二高薪水。 Have no idea what to do :/
不知道该怎么办:/
Tried searching for answers but didn't quite get what I wanted. 试图寻找答案,但没有完全得到我想要的。
If you just want the second more high salary, you can use limit and offset. 如果您只想再拿高一点的薪水,可以使用限制和补偿。
Would not it be a valid solution? 这不是一个有效的解决方案吗?
select e.salary,d.department_name
from oehr_employees e
join oehr_departments d on(e.department_id = d.department_id)
ORDER BY e.salary DESC LIMIT 1 OFFSET 1
If you want to do it using subqueries, you can try like following to get the details of employee(s) and department(s) with 2nd highest salary. 如果要使用子查询来执行此操作,可以尝试执行以下操作,以获取薪水第二高的员工和部门的详细信息。
select e.name,e.salary,d.department_id,d.department_name
from
oehr_employees e
join oehr_departments d on e.department_id = d.department_id
WHERE e.salary IN (SELECT Max(salary)
FROM oehr_employees
WHERE salary NOT IN (SELECT Max(salary)
FROM oehr_employees));
Use ROW_NUMBER(): 使用ROW_NUMBER():
SELECT *
FROM (
SELECT
e.employee_id,
d.department_id,
e.salary,
ROW_NUMBER() OVER(ORDER BY e.salary DESC) rn
FROM oehr_employees e
INNER JOIN oehr_departments d
ON e.department_id = d.department_id
) x WHERE rn = 2
I would just modify your query a bit and add limit 1
: 我只是稍微修改一下查询并添加
limit 1
:
select e.*, d.department_name
from oehr_employees e join
oehr_departments d
on e.department_id = d.department_id)
where e.salary < (select max(e2.salary) from oehr_employees e2)
order by e.salary desc
limit 1;
This seems to meet the arcane requirement of using subqueries. 这似乎满足使用子查询的不可思议的要求。 And it is a reasonable approach.
这是一种合理的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.