I have table like this.
I want to find the max salary department wise and the name of employee who has it. I ran MySql query
select concat(First_name,' ',Last_name) as Name,max(SALARY)
from Employee
group by Department;
which gives result as shown below.
In which max(SALARY) is correct but Emplyoee name is wrong.How to get both correct?
Try this:
SELECT concat(First_name,' ',Last_name) as Name,SALARY FROM Employee WHERE salary IN (SELECT MAX(SALARY) FROM Employee GROUP BY Department);
this will help you.
If you want only max
SELECT first_name,department,salary FROM Employees WHERE salary IN (SELECT max(salary) From employees GROUP BY department)
If you want max and min
select department, first_name, salary from employees e1 where salary in ((select max(salary) from employees where department=e1.department), (select min(salary) from employees where department=e1.department)) order by department
You have to find out what the max salary is per department, and then find the employee(s) in that department who have that salary.
Use a CTE or a Correlated SubQuery.
With myCTE (dept, maxsalary)
as (
Select dept, max(salary) over (partition by dept) from EmployeeTable)
Select concat(e.firstname, e.lastname), e. salary
from EmployeeTable e where e.Dept = myCTE.dept and e.Salary = myCTE.salary
Here is a correct solution:
SELECT concat(e.First_name, ' ', e.Last_name) as Name, e.SALARY
FROM Employee e
WHERE salary = (SELECT MAX(SALARY) FROM Employee e2 WHERE e2.Department = e.Department);
SELECT t.name,t.dept_id,temp.max
FROM employee as t
JOIN (SELECT dept, MAX(salary) AS max
FROM employee
GROUP BY dept_id) as temp
on t.dept_id=temp.dept_id and t.salary=temp.max
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.