### N（th）最高工资查询

``````SELECT * FROM Employee Emp1
WHERE (N-1) = (
SELECT COUNT(DISTINCT(Emp2.Salary))
FROM Employee Emp2
WHERE Emp2.Salary > Emp1.Salary
)
``````

``````WHERE Emp2.Salary > Emp1.Salary
``````

``````WHERE (N-1) = <subquery>
``````

#### 2 个答案:

``````SELECT * FROM Employee Emp1
CROSS APPLY
(
SELECT COUNT(DISTINCT(Emp2.Salary)) AS NHigher
FROM Employee Emp2
WHERE Emp2.Salary > Emp1.Salary
) X;
``````

e.g。在SQL Server 2012中，要获取第二高的薪水：

``````SELECT *
FROM Employee Emp1
ORDER BY SALARY DESC
OFFSET 1 ROWS FETCH NEXT 1 ROWS ONLY;
``````

1. 拿Nth最高薪

2. 让有薪水的员工

3. 现在你可以通过以下方式实现它：

第一个解决方案分组工资：

``````SELECT * FROM Employee as emp
WHERE emp.Salary =
(
SELECT TOP 1 t.Salary FROM
(
SELECT TOP N(th) e.Salary FROM Employee as e
Group by e.Salary
Order By e.Salary
) as t
ORDER BY t.Salary DESC
)
``````

第二个解决方案DISTINCT salarys：

``````SELECT * FROM Employee as emp
WHERE emp.Salary =
(
SELECT TOP 1 t.Salary FROM
(
SELECT DISTINCT TOP N(th) e.Salary FROM Employee as e
Order By e.Salary
) as t
ORDER BY t.Salary DESC
)
``````