SQL 语句实现排序问题!
2013-11-18 23:34
363 查看
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
*/
--符合要求。
--现在假设测试数据:创建临时表 #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
*/
--符合要求。
相关文章推荐
- sqlite3 实现批量处理 sql语句,避免频繁操作数据库,从而影响性能的问题
- SQL分页排序的实现与分页数据重复问题——以Oracle rownum为例
- 关于统计的一个sql问题,使用动态sql语句实现。
- 求救!胜负比率计算问题?如何用SQL语句实现?(存储过程也可以)
- sql语句使用case when实现列排序
- DataTable实现列位置交换,用于SQL语句无法解决字段页面显示顺序问题
- sql语句排序问题
- 数据库分类排序的sql语句问题
- SQL语句实现查询一段时间内的数据中要注意的细节问题
- [导入]实现SQL语句中,按照in 中的顺序排序的方法
- SQL语句实现按关健字模糊查询,并按匹配度排序
- DataTable实现列位置交换,用于SQL语句无法解决字段页面显示顺序问题
- SQL语句实现按关健字模糊查询,并按匹配度排序
- C#拼接SQL语句,SQL Server 2005+,多行多列大数据量情况下,使用ROW_NUMBER实现的高效分页排序
- 多音字按拼音首字母排序sql语句的问题解决方案
- SQL分页排序的实现与分页数据重复问题——以Oracle rownum为例
- SQL语句实现表中字段的组合累加排序
- Sql语句排序的算法 是不是应用经典算法冒泡法实现的?