1. 程式人生 > >MySQL查詢每個部門的最高薪水

MySQL查詢每個部門的最高薪水

假設有兩個表Department和Employee。

department的表結構如下:

+-------+-------------+------+-----+---------+----------------+
| Field | Type        | Null | Key | Default | Extra          |
+-------+-------------+------+-----+---------+----------------+
| Id    | int(11)     | NO   | PRI | NULL    | auto_increment |
| Name  | varchar(60) | YES  |     | NULL    |                |
+-------+-------------+------+-----+---------+----------------+

employee表結構如下:

+--------------+-------------+------+-----+---------+----------------+
| Field        | Type        | Null | Key | Default | Extra          |
+--------------+-------------+------+-----+---------+----------------+
| Id           | int(11)     | NO   | PRI | NULL    | auto_increment |
| Name         | varchar(60) | YES  |     | NULL    |                |
| Salary       | double(9,2) | YES  |     | NULL    |                |
| DepartmentId | int(11)     | YES  | MUL | NULL    |                |
+--------------+-------------+------+-----+---------+----------------+

現在要查詢每個部門的最高薪水,查詢語句如下:

SELECT
	d. NAME Department,
	e. NAME Employee,
	e.Salary Salary
FROM
	Employee e
JOIN (
	SELECT
		MAX(Salary) max,
		DepartmentId
	FROM
		Employee
	GROUP BY
		DepartmentId
) g ON e.DepartmentId = g.DepartmentId
JOIN Department d ON (e.DepartmentId = d.Id)
WHERE
	e.Salary = g.max;