SQL 查询数据时按某列排序后增加排名列,需排名的列值相等时排名相同,即如需排名列数组为:9,9,8,7,7,6
添加的排名列数组需要显示为两种:
第一种:1,1,3,4,4,6 (这种排名方法应该是最普遍的排名方法啦) 或者
第二种:1,1,2,3,3,4 (某些特殊情况需要)
- --现在假设测试数据:创建临时表 #score 并插入数据
-
-
create table #score(id int, points float) --id 为学号和points为成绩
-
-
insert #score select 1, 90
-
union all select 2, 85
-
union all select 3, 83
-
union all select 4, 85
-
union all select 5, 92
-
-
--测试得到上述第一种排名显示,SQL如下:
-
-
Select
-
points,
-
(Select Count(1)+1 from #score Where points>A.points) As 排名
-
from #score A Order By 排名
-
-
--结果如下:
-
-
/*
-
points 排名
-
92.0 1
-
90.0 2
-
85.0 3
-
85.0 3
-
83.0 5
-
*/
-
--符合要求。
-
-
--测试得到上述第二种排名显示,SQL如下:
-
-
Select
-
points,
-
(Select Count(Distinct points)+1 from #score Where points>A.points) As 排名
-
from #score A
-
Order By 排名
-
--结果
-
-
/*
-
points 排名
-
92.0 1
-
90.0 2
-
85.0 3
-
85.0 3
-
83.0 4
-
*/
- --符合要求。
阅读(1208) | 评论(0) | 转发(0) |