排序函数可以用来协助给结果集增加位置信息。SQL SERVER 2008只有四个排序函数,介绍如下:

ROW_NUMBER:返回结果集中给定行的序号
RANK:基于给定行集合的选择顺序,给出行的位置。如有一些值连在一起,位置间有空隙
     如两个值在第一位,然后下一个值将在第三位
DENSE_RANK:同RANK一样,但没有在顺序中留下空隙。RANK肯能位1,2,2,4,4,6,6;DENSE_RANK为:1,2,2,3,3,4,4-NTILE:DENSE_RANK用于将排名分为若干部分。如果一个表有100个值,可以使用NTITL(2)将前五十个数定为1,后五十个数定为2 

示例如下:

CREATE VIEW contractSubset  
AS
    SELECT TOP 20 *
    FROM Person.Person 
    WHERE FirstName like 'b%'  
    
select firstname,
      (select COUNT(*) 
       from contractSubset as c
       where c.FirstName <contractSubset.FirstName)+1 As Rank
from contractSubset 
order by FirstName            
    

SELECT firstname,
    ROW_NUMBER() OVER (ORDER BY firstname) AS 'ROW_NUMBER',
    RANK() OVER (ORDER BY firstname) as 'RANK',
    DENSE_RANK() OVER (ORDER BY firstname) as 'DENSE_RANK',
    NTILE(4) OVER (ORDER BY firstname) AS 'NTILE(4)'      
from contractSubset 
order by FirstName