排名函数的用法

/*-----------------------------------------------
--说明:排序函数的使用
--永恒de影ミ
--2010/03/04
------------------------------------------------
*/
--示例数据
declare @a table (a int,b int,n int)
insert @a 
select 1,2,1
union all
select 1,3,2
union all
select 2,2,2
union all
select 3,2,4
union all
select 4,2,4
union all
select 5,2,5

/*--原始数据
a           b           n
----------- ----------- -----------
1           2           1
1           3           2
2           2           2
3           2           4
4           2           4
5           2           5
(6 行受影响)
--
*/

--sql2005
select Dense_Rank() over(order by n),* from @a

--sql2000
select *,(select count(distinct n) from @a where n<=a.n) from @a  a

/*--结果
a           b           n           
----------- ----------- ----------- -----------
1           2           1           1
1           3           2           2
2           2           2           2
3           2           4           3
4           2           4           3
5           2           5           4
(6 行受影响)
--
*/
--名次生成时重复时保留名次空缺
SELECT *,排名=(SELECT COUNT(n) FROM @a WHERE n>a.n)+1
FROM @a a
ORDER BY 排名

/*--结果
a           b           n           排名
----------- ----------- ----------- -----------
5           2           5           1
3           2           4           2
4           2           4           2
1           3           2           4
2           2           2           4
1           2           1           6

(6 行受影响)
--
*/
原文地址:https://www.cnblogs.com/wequst/p/1663893.html