SQL Fiddle:可以線上執行SQL語法測試的網頁。
選擇資料庫為MS SQL Server 2017並套用下述大大的教學語法,則可以線上模擬SQL的執行結果。
參考文章:
[演算法][SQL]演算法挑戰系列(4)-Department Top Three Salaries
https://ithelp.ithome.com.tw/articles/10198443
Build Schema :
Create table Employee (Id int, Name varchar(255), Salary int, DepartmentId int)
Create table Department (Id int, Name varchar(255))
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')
insert into Employee (Id, Name, Salary, DepartmentId) values ('5', 'Janet', '69000', '1')
insert into Employee (Id, Name, Salary, DepartmentId) values ('6', 'Randy', '85000', '1')
insert into Department (Id, Name) values ('1', 'IT')
insert into Department (Id, Name) values ('2', 'Sales')
Run SQL :
/*SELECT題目要的欄位*/
SELECT d.Name Department,Employee,Salary
FROM
/*先在內部做一個子查詢,主要是為了幫各部門的員工薪水做排名*/
(SELECT Name Employee,Salary,DepartmentId
/*這裡用DENSE_RANK()做排名 OVER()內PARTITION BY指定的欄位是群組 ORDER BY是以薪水排序*/
,DENSE_RANK() OVER (PARTITION BY e.DepartmentId ORDER BY e.Salary DESC) AS SRank
FROM Employee e) e
/*JOIN部門檔,帶出部門名稱*/
LEFT JOIN Department d ON e.DepartmentId = d.Id
/*查詢條件是名次在前三名,以及在公司部門內的人員(因為我在解題的時候有些員工會是部門檔沒有的部門Id)*/
WHERE SRank<=3 AND d.Name IS NOT NULL
留言列表