MySQL版本为5.6
使用的软件 navicate
题目:统计每个部门中薪酬最高的员工
知识点:分组排序,多表查询
解题思路:
CREATE TABLE `EMPLOYEE` ( `ID` varchar(255), `Name` varchar(255), `Salary` varchar(255), `DepartmentID` varchar(255) ); INSERT INTO `EMPLOYEE` VALUES ('1', 'Joe', '70000', '1'); INSERT INTO `EMPLOYEE` VALUES ('2', 'Henry', '80000', '2'); INSERT INTO `EMPLOYEE` VALUES ('3', 'Jane', '60000', '2'); INSERT INTO `EMPLOYEE` VALUES ('4', 'Ben', '90000', '1'); CREATE TABLE `DEPARTMENT` ( `ID` varchar(255), `DEPARTMENT` varchar(255) ); INSERT INTO `DEPARTMENT` VALUES ('1', 'IT'); INSERT INTO `DEPARTMENT` VALUES ('2', 'Sales');
# 方法一 SELECT `Name`, Salary, DEPARTMENT FROM ( EMPLOYEE INNER JOIN DEPARTMENT ON EMPLOYEE.DepartmentID = DEPARTMENT.ID ) INNER JOIN ( SELECT DepartmentID, MAX( Salary ) AS MAX_Salary FROM EMPLOYEE GROUP BY DepartmentID ) AS T ON EMPLOYEE.DepartmentID = T.DepartmentID AND EMPLOYEE.Salary = T.MAX_Salary; # 方法二 SELECT * FROM (SELECT `Name` ,Salary,DEPARTMENT as D FROM EMPLOYEE INNER JOIN DEPARTMENT ON EMPLOYEE.DepartmentID = DEPARTMENT.ID ORDER BY D,Salary DESC ) as t GROUP BY D ;