2
votes

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

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.

4
Among everyone or among his department employees? - Amir Molaei
Subqueries are part of the brief? - Strawberry

4 Answers

0
votes

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
0
votes

Use 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
0
votes

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)); 
0
votes

I would just modify your query a bit and add 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.