使用 CTE 找到第 n 個最高薪水
員工表:
| ID | FirstName | LastName | Gender | Salary |
+------+-----------+----------+--------+--------+
| `1` | Jahangir | Alam | Male | 70000 |
| `2` | Arifur | Rahman | Male | 60000 |
| `3` | Oli | Ahammed | Male | 45000 |
| `4` | Sima | Sultana | Female | 70000 |
| `5` | Sudeepta | Roy | Male | 80000 |
+------+-----------+----------+--------+--------+
CTE(通用表格表示式):
WITH RESULT AS
(
SELECT SALARY,
DENSE_RANK() OVER (ORDER BY SALARY DESC) AS DENSERANK
FROM EMPLOYEES
)
SELECT TOP 1 SALARY
FROM RESULT
WHERE DENSERANK = 1
要找到第二高的薪水,只需將 N 替換為 2.同樣,要找到第三高薪,只需將 N 替換為 3。