一、題目名稱sql
Department Highest Salary(部門內最高工資)數據庫
二、題目地址命令行
https://leetcode.com/problems/department-highest-salary/code
三、題目內容leetcode
表Employee包括四列:Id、Name、Salary、DepartmentIdget
+----+-------+--------+--------------+ | Id | Name | Salary | DepartmentId | +----+-------+--------+--------------+ | 1 | Joe | 70000 | 1 | | 2 | Henry | 80000 | 2 | | 3 | Sam | 60000 | 2 | | 4 | Max | 90000 | 1 | +----+-------+--------+--------------+
表Department表中包括了公司的全部部門class
+----+----------+ | Id | Name | +----+----------+ | 1 | IT | | 2 | Sales | +----+----------+
現要求寫一個SQL,求出某一部門內領取最高工資的員工。數據
+------------+----------+--------+ | Department | Employee | Salary | +------------+----------+--------+ | IT | Max | 90000 | | Sales | Henry | 80000 | +------------+----------+--------+
四、初始化數據庫腳本腳本
在MySQL數據庫中創建一個名爲LEETCODE的數據庫,用MySQL命令行中的source命令執行下面腳本:co
-- 執行腳本前必須創建名爲LEETCODE的DATABASE USE LEETCODE; DROP TABLE IF EXISTS Employee; CREATE TABLE Employee ( Id INT NOT NULL PRIMARY KEY, Name VARCHAR(50), Salary INT, DepartmentId INT ); INSERT INTO Employee (Id, Name, Salary, DepartmentId) VALUES (1, 'Joe', 70000, 1); INSERT INTO Employee (Id, Name, Salary, DepartmentId) VALUES (2, 'Henry', 80000, 2); INSERT INTO Employee (Id, Name, Salary, DepartmentId) VALUES (3, 'Sam', 60000, 2); INSERT INTO Employee (Id, Name, Salary, DepartmentId) VALUES (4, 'Max', 90000, 1); DROP TABLE IF EXISTS Department; CREATE TABLE Department ( Id INT NOT NULL PRIMARY KEY, Name VARCHAR(50) ); INSERT INTO Department (Id, Name) VALUES (1, 'IT'); INSERT INTO Department (Id, Name) VALUES (2, 'Sales');
五、解題SQL1
一個思路是,先求出各個部門的最高工資,再考察Employee表中,工資數等於所在部門的最高工資的員工,即爲所求。
SELECT D.Name AS Department, E.Name AS Employee, MAXS_D.MAXS AS Salary FROM Employee AS E, Department AS D, ( SELECT MAX(Salary) AS MAXS, DepartmentId FROM Employee GROUP BY DepartmentId) AS MAXS_D WHERE E.Salary = MAXS_D.MAXS AND E.DepartmentId = D.Id AND E.DepartmentId = MAXS_D.DepartmentId;
六、解題SQL2
另外一個思路是,在同一部門中,工資大於等於該部門全部員工的員工,即爲所求。
SELECT D.Name AS Department, E.Name AS Employee, E.Salary AS Salary FROM Employee AS E, Department AS D WHERE E.DepartmentId = D.Id AND Salary >= ALL( SELECT Salary FROM Employee E_TMP WHERE E_TMP.DepartmentId = E.DepartmentId);
END