在 SQL Server 中,我试图获得前 5 名的薪水。
我有薪水
5000
5000
4500
4500
3000
2000
1000
500
400
我想得到
5000
5000
4500
4500
3000
2000
1000
在 SQL Server 中,我试图获得前 5 名的薪水。
我有薪水
5000
5000
4500
4500
3000
2000
1000
500
400
我想得到
5000
5000
4500
4500
3000
2000
1000
SELECT TOP 5 salary FROM your_table
ORDER BY salary DESC
如果您想获得前 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
select salary
from
(
select salary,
dense_rank() over(order by salary desc) as rn
from YourTable
) as T
where rn <= 5
试用SE-Data
SELECT TOP 5 Salary
FROM [Table]
GROUP BY Salary
ORDER BY Salary DESC
您需要对查询进行分组以避免重复的薪水。