如何在SQL Server中使用rank函数

时间:2017-09-25 11:02:23

标签: sql sql-server

我正在努力获得第五到第十之间的记录。 我在sql server

中使用以下查询

Plz让我纠正

SELECT ID,
       code,
       first name,
       last name,
       RANK() OVER(ORDER BY code) AS rk
FROM tbl_em_employees
WHERE rk BETWEEN 5 AND 10;

它给我错误

  

rk无效。

3 个答案:

答案 0 :(得分:4)

您无法在WHERE中引用列别名,因此您必须使用子查询或公用表表达式(CTE):

WITH CTE AS
(
    Select ID, code, first name, last name, 
        rank() over (order by code) as rk 
    from tbl_em_employees 
)
SELECT ID, code, first name, last name
FROM CTE
WHERE rk between 5 and 10

答案 1 :(得分:0)

SELECT ID, code, first name, last name FROM
(
    Select ID, code, first name, last name, 
        rank() over (order by code) as rk 
    from tbl_em_employees 
)

WHERE rk between 5 and 10

答案 2 :(得分:-1)

你可以使用这样的等级函数: -

RANK ( ) OVER ( [ partition_by_clause ] order_by_clause )  

如需更多参考,请查看以下链接: - https://docs.microsoft.com/en-us/sql/t-sql/functions/rank-transact-sql