您好,登錄后才能下訂單哦!
本篇文章為大家展示了SQL中怎么利用LeetCode求最高薪水,內容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。
The Employee table holds all employees. Every employee has an Id, a salary, and there is also a column for the department Id.
+----+-------+--------+--------------+
| Id | Name | Salary | DepartmentId |
+----+-------+--------+--------------+
| 1 | Joe | 70000 | 1 |
| 2 | Henry | 80000 | 2 |
| 3 | Sam | 60000 | 2 |
| 4 | Max | 90000 | 1 |
+----+-------+--------+--------------+
The Department table holds all departments of the company.
+----+----------+
| Id | Name |
+----+----------+
| 1 | IT |
| 2 | Sales |
+----+----------+
Write a SQL query to find employees who have the highest salary in each of the departments. For the above tables, Max has the highest salary in the IT department and Henry has the highest salary in the Sales department.
+------------+----------+--------+
| Department | Employee | Salary |
+------------+----------+--------+
| IT | Max | 90000 |
| Sales | Henry | 80000 |
+------------+----------+--------+
這道題讓給了我們兩張表,Employee表和Department表,讓我們找系里面薪水最高的人的,實際上這題是Second Highest Salary和Combine Two Tables的結合題,我們既需要聯合兩表,又要找到最高薪水,那么我們首先讓兩個表內交起來,然后將結果表需要的列都標明,然后就是要找最高的薪水,我們用Max關鍵字來實現,參見代碼如下:
解法一:
SELECT d.Name AS Department, e1.Name AS Employee, e1.Salary FROM Employee e1 JOIN Department d ON e1.DepartmentId = d.Id WHERE Salary IN (SELECT MAX(Salary) FROM Employee e2 WHERE e1.DepartmentId = e2.DepartmentId);
我們也可以不用Join關鍵字,直接用Where將兩表連起來,然后找最高薪水的方法和上面相同:
解法二:
SELECT d.Name AS Department, e.Name AS Employee, e.Salary FROM Employee e, Department d WHERE e.DepartmentId = d.Id AND e.Salary = (SELECT MAX(Salary) FROM Employee e2 WHERE e2.DepartmentId = d.Id);
下面這種方法沒用用到Max關鍵字,而是用了>=符號,實現的效果跟Max關鍵字相同,參見代碼如下:
解法三:
SELECT d.Name AS Department, e.Name AS Employee, e.Salary FROM Employee e, Department d WHERE e.DepartmentId = d.Id AND e.Salary >= ALL (SELECT Salary FROM Employee e2 WHERE e2.DepartmentId = d.Id);
上述內容就是SQL中怎么利用LeetCode求最高薪水,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。