I have database with name, salary and department of employees. I need a query for getting employee(s) with highest salaries in each department.
Database:
create table test(
employee_name VARCHAR(255),
department VARCHAR(255),
salary INT
);
Data:
INSERT INTO test(employee_name, department, salary) VALUES
("John", "DepartmentA", 1500),
("Sarah","DepartmentA", 1600),
("Romel","DepartmentA", 1400),
("Victoria","DepartmentB", 1400),
("Maria", "DepartmentB", 1600);
My tries:
1.1 WHERE MAX(salary) = salary GROUP BY department
SELECT employee_name, salary FROM test WHERE MAX(salary) = salary GROUP BY department;
ERROR 1111 (HY000): Invalid use of group function
1.2. when I replace MAX(salary) with hardcoded value, it works as I expect:
SELECT employee_name, salary FROM test WHERE 1600 = salary GROUP BY department;
+---------------+--------+
| employee_name | salary |
+---------------+--------+
| Sarah | 1600 |
| Maria | 1600 |
+---------------+--------+
2 rows in set (0.00 sec)
Wrong answer with having clause (single result, not per department):
SELECT employee_name, salary FROM test GROUP BY department HAVING MAX(salary) = salary;
+---------------+--------+ | employee_name | salary | +---------------+--------+ | Maria | 1600 | +---------------+--------+ 1 row in set (0.00 sec)
What I expect as result:
Sarah, DepartmentA
Maria, DepartmentB