1

在 SQL Server 中,我试图获得前 5 名的薪水。

我有薪水

5000
5000
4500
4500
3000
2000 
1000
500
400

我想得到

5000
5000
4500
4500
3000
2000
1000 
4

5 回答 5

3
SELECT TOP 5 salary FROM your_table
ORDER BY salary DESC
于 2012-04-13T11:07:00.470 回答
2

如果您想获得前 5 名不同的薪水(无论相同金额出现多少次),您需要使用DENSE_RANK()排名函数和 CTE 来实现:

DECLARE @salaries TABLE (salary DECIMAL(18,4))

INSERT INTO @salaries VALUES(5000)
INSERT INTO @salaries VALUES(5000)
INSERT INTO @salaries VALUES(4500)
INSERT INTO @salaries VALUES(4500)
INSERT INTO @salaries VALUES(3000)
INSERT INTO @salaries VALUES(2000)
INSERT INTO @salaries VALUES(1000)
INSERT INTO @salaries VALUES(500)
INSERT INTO @salaries VALUES(400)

;WITH SalariesRanked AS
(
    SELECT 
        Salary, 
        SalaryNumber = DENSE_RANK() OVER(ORDER BY Salary DESC)
    FROM    
        @salaries
)
SELECT salary
FROM SalariesRanked 
WHERE SalaryNumber <= 5

这会产生如下输出:

salary
5000.0000
5000.0000
4500.0000
4500.0000
3000.0000
2000.0000
1000.0000
于 2012-04-13T11:31:18.450 回答
1
select salary
from
  (
    select salary,
           dense_rank() over(order by salary desc) as rn
    from YourTable
  ) as T
where rn <= 5

试用SE-Data

于 2012-04-13T11:30:58.343 回答
0

看看使用TOP (Transact-SQL)

于 2012-04-13T11:07:05.257 回答
0
SELECT TOP 5 Salary
FROM [Table]
GROUP BY Salary
ORDER BY Salary DESC

您需要对查询进行分组以避免重复的薪水。

于 2012-04-13T14:28:04.510 回答