SQL COMPLEX QUERY- find max and min salary department wise from employee table
Table Name: EMPLOYEE
Approach: Write a sub query which will partition the data based on each department and then identify the record with maximum and minimum salary for each of the partitioned department. Finally, from the main query fetch only the data which matches the maximum and minimum salary returned from the sub query.
Expected Output
Again there are many way to do this and also we can use a few window functions to achieve the same result. As an added challenge, try out solving this query using a different window function and then comment out your query.
–heighest or minimum salary from each department
SELECT * FROM EMPLOYEES EMP JOIN
(
SELECT SALARY,EMPLOYEE_ID,
min(salary) OVER (partition by department_id) AS MIN_SALARY_RN,
max(salary) OVER (partition by department_id) AS MAX_SALARY_RN
FROM employees EMP
) emp_new
ON EMP.EMPLOYEE_ID = EMP_NEW.EMPLOYEE_ID
AND (EMP.SALARY = EMP_NEW.MIN_SALARY_RN OR EMP.SALARY = EMP_NEW.MAX_SALARY_RN);