I’m working with two database tables: employees and departments. Each employee record contains a dept_id that links to a department in the departments table.
My basic JOIN query works fine:
SELECT surname, department_name, salary_avg
FROM employees INNER JOIN departments
ON employees.dept_id = departments.dept_id
WHERE department_name = 'Engineering'
However, I need to find the employee with the highest salary specifically from the Engineering department. My first attempt failed:
SELECT surname, salary_avg FROM (
SELECT surname, department_name, salary_avg
FROM employees INNER JOIN departments
ON employees.dept_id = departments.dept_id
WHERE department_name = 'Engineering'
) AS temp_result
WHERE salary_avg = (SELECT MAX(salary_avg) FROM temp_result);
This gives an error saying temp_result table doesn’t exist.
I found a workaround by duplicating the entire JOIN:
SELECT surname, salary_avg FROM (
SELECT surname, department_name, salary_avg
FROM employees INNER JOIN departments
ON employees.dept_id = departments.dept_id
WHERE department_name = 'Engineering'
) AS temp_result
WHERE salary_avg = (SELECT MAX(salary_avg) FROM (
SELECT surname, department_name, salary_avg
FROM employees INNER JOIN departments
ON employees.dept_id = departments.dept_id
WHERE department_name = 'Engineering'
) AS temp_result_two);
This works but seems inefficient. Is there a cleaner way to achieve this without repeating the JOIN operation twice?