Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1239275
  • 博文数量: 510
  • 博客积分: 20296
  • 博客等级: 上将
  • 技术积分: 4680
  • 用 户 组: 普通用户
  • 注册时间: 2007-10-30 03:58
文章存档

2011年(13)

2010年(92)

2009年(242)

2008年(163)

我的朋友

分类: 数据库开发技术

2010-09-16 20:43:18

    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. --符合要求。

阅读(1110) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~