SQL 语句实现排序问题!

 SQL 查询数据时按某列排序后增加排名列,需排名的列值相等时排名相同,即如需排名列数组为:9,9,8,7,7,6     添加的排名列数组需要显示为两种:   第一种:1,1,3,4,4,6 (这种排名方法应该是最普遍的排名方法啦) 或者   第二种:1,1,2,3,3,4 (某些特殊情况需要)

 

  1. --现在假设测试数据:创建临时表 #score 并插入数据
  2.  create table #score(id int, points float) --id 为学号和points为成绩
  3.   insert #score select 1, 90
  4.   union all select 2, 85
  5.   union all select 3, 83
  6.   union all select 4, 85
  7.   union all select 5, 92
  8.   --测试得到上述第一种排名显示,SQL如下:
  9.   Select
  10.   points,
  11.   (Select Count(1)+1 from #score Where points>A.points) As 排名
  12.   from #score A Order By 排名
  13.  
  14.   --结果如下:
  15.   /*
  16. points 排名
  17.   92.0 1
  18.   90.0 2
  19.   85.0 3
  20.   85.0 3
  21.   83.0 5
  22.   */
  23. --符合要求。
  24.  
  25.  --测试得到上述第二种排名显示,SQL如下:
  26.   Select
  27.   points,
  28.   (Select Count(Distinct points)+1 from #score Where points>A.points) As 排名
  29.   from #score A
  30.   Order By 排名
  31.   --结果
  32.   /*
  33. points 排名
  34.   92.0 1
  35.   90.0 2
  36.   85.0 3
  37.   85.0 3
  38.   83.0 4
  39.   */
  40. --符合要求。
Top
收藏
关注
评论
原文地址:https://www.cnblogs.com/alanjl/p/3430515.html