增加排名列SQL语句(需排名的列值相等时排名相同)
2012-03-12 11:24
309 查看
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
*/
--符合要求。
添加的排名列数组需要显示为两种:
第一种: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
*/
--符合要求。
相关文章推荐
- 增加排名列SQL语句(需排名的列值相等时排名相同)
- 在SQL语句中添加分数相同的项的相同排名
- 增加一列跟删除一列的Sql语句
- sql语句在某一字段所有数据后面加上相同的字符串
- SQL语句增加字段、修改字段、修改类型、修改默认值
- ORACLE中通过SQL语句(alter table)来增加、删除、修改字段
- sql语句求排名
- sql替换语句 批量修改、增加、删除字段内容
- 统计查询两列相同的sql语句
- SQL学习之查询技巧 查询第3的数据 用一条语句分组,排序 并查询某一排名
- 查询表中相同数据的sql语句[转]
- SQL语句增加虚拟字段,并根据情况显示不同的数据。。。(已阅。。。未阅。。)
- SQL学习之查询技巧 查询第3的数据 用一条语句分组,排序 并查询某一排名
- SQL语句 从一个表读取数据,写入到另一个表的相同字段中
- SQL语句增加列、修改列类型、修改列、删除列
- SQL迅速增加表中记录语句
- Mysql中批量删除相同表前缀的数据表 sql语句
- 删除SQL数据库中相同记录的SQL语句
- SQL语句查询相同条目并记录重复次数
- Mysql将查询后的数据进行排名的SQL语句