Max and Min Sal With Employee Name in One Query

How to get employee name with minimum and maximum of salary for second employee name with same salary value in mysql?

You can use the ROW_NUMBER analytic function to get the details of the employee with the lowest salary and the second employee when ordered by descending salary and then by name:

SELECT emp_name,
salary
FROM (
SELECT emp_name,
salary,
ROW_NUMBER() OVER (ORDER BY salary ASC, emp_name ASC) AS rn_min,
ROW_NUMBER() OVER (ORDER BY salary DESC, emp_name ASC) AS rn_max
FROM odd_empcop
) e
WHERE rn_min = 1
OR rn_max = 2;

Which, for the sample data:

CREATE TABLE odd_empcop (
salary NUMERIC(10,2),
emp_name VARCHAR(20)
);

INSERT INTO odd_empcop (emp_name, salary)
SELECT 'Gautham', 2000 FROM DUAL UNION ALL
SELECT 'Melinda', 8000 FROM DUAL UNION ALL
SELECT 'Cory', 8000 FROM DUAL UNION ALL
SELECT 'Vikram', 8000 FROM DUAL;

Outputs:



















emp_namesalary
Melinda8000.00
Gautham2000.00

SQL GROUP BY and MIN to find people with minimum salary in each department

Instead fo a IN clause you can also use an inner join

SELECT first_name, last_name, salary, department_id  
FROM employees
INNER JOIN ( SELECT department_id, MIN(salary) min_sal
FROM employees
GROUP BY department_id
) t on t.department_id =employees.department_id
and employees.salary = t.min_sal;

this should be better for performance

How to get the maximum and minimum salary of all the departments along with department name,manager id, manager name of each department?

You have to make two JOINs to the employees table : first join between employee and manager_id, and second join between employee and department_id.

Something like this should work:

SELECT 
d.department_id,
d.department_name,
d.manager_id,
m.first_name,
max(e.salary) as Maximum_Salary,
min(e.salary) Minimum_Salary
FROM departments d
LEFT JOIN employees e ON d.department_id=e.department_id
LEFT JOIN employees m ON d.manager_id = m.employee_id
GROUP BY d.department_id, d.department_name,
d.manager_id, m.first_name
ORDER BY d.department_id;


Related Topics



Leave a reply



Submit