SQL COMPLEX QUERY- find max Nth and min Nth salary department wise from employee table

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.

Question seems to be last post where we have calculated max or min department wise salary but when it comes to end than that logic won’t work instead we can use windows row_num() function

Solution:

–nth highest or nth lowest salary from each department from Employee table
–highest
SELECT * FROM(
SELECT
ROW_NUMBER() OVER (partition by department_id ORDER BY salary) AS MIN_SALARY_RN,
ROW_NUMBER() OVER (partition by department_id ORDER BY salary DESC) AS MAX_SALARY_RN,
EMP.*
FROM employees EMP
) WHERE MIN_SALARY_RN=1 OR MAX_SALARY_RN=1;
–second highest
SELECT * FROM(
SELECT
ROW_NUMBER() OVER (partition by department_id ORDER BY salary) AS MIN_SALARY_RN,
ROW_NUMBER() OVER (partition by department_id ORDER BY salary DESC) AS MAX_SALARY_RN,
EMP.*
FROM employees EMP
) WHERE MIN_SALARY_RN=2 OR MAX_SALARY_RN=2;

–above query even will work for second minimum and second highest query logic we just have to adjust row_num

Popular posts from this blog

Window function in PySpark with Joins example using 2 Dataframes (inner join)

Complex SQL: fetch the users who logged in consecutively 3 or more times (lead perfect example)

Credit Card Data Analysis using PySpark (how to use auto broadcast join after disabling it)