I need to write SQL query that will get the employees with the highest pay from each department separately and return name and pay of the employee and the department name they are in.
employees
+----+-------+------+---------------+
| id | name | pay | department_id |
+----+-------+------+---------------+
| 1 | Bob | 1200 | 1 |
| 2 | Rob | 600 | 2 |
| 3 | Tom | 800 | 2 |
| 4 | Pam | 900 | 1 |
| 5 | Dave | 1200 | 1 |
+----+-------+------+---------------+
departments
+----+-----------+
| id | name |
+----+-----------+
| 1 | IT |
| 2 | Marketing |
+----+-----------+
This query returns just the first employee from each department with the highest pay in the table, but I would like to get all the employees, that have the highest pay, in this case both Bob and Dave from IT and Tom from Marketing.
SELECT d.name,e.name,e.pay FROM employees e JOIN departments d
ON e.department_id = d.id GROUP BY d.id HAVING MAX(e.pay)
The correct result should be:
+-----------+-------+------+
| IT | Bob | 1200 |
| IT | Dave | 1200 |
| Marketing | Tom | 800 |
+-----------+-------+------+