请教一个关于排名的问题,看大家有没有想过这个问题
create table Scores
(
id int identity(1,1) primary key,
XingMing varchar(20) not null,
Score int not null
)
insert Scores select '陈七 ',100
insert Scores select '黄八 ',80
insert Scores select '莉莉 ',90
insert Scores select '李四 ',90
insert Scores select '张三 ',50
select * from Scores
select *,[排名]=(select count(*) from Scores where tmp.Score <=Score) from Scores tmp
drop table Scores
下面是我执行的结果,但是我想因为莉莉和李四都是第3,那么习惯上张三就应该是6了,这个该如何实现呢
1陈七1001
2黄八804
3莉莉903
4李四903
5张三505
最终想要的结果
1陈七1001
2黄八804
3莉莉903
4李四903
5张三506
[解决办法]
select *,[排名]=(select count(*)+1 from Scores where tmp.Score <Score and tmp.id <> id) from Scores tmp
id XingMing Score 排名
----------- -------------------- ----------- -----------
1 陈七 100 1
2 黄八 80 4
3 莉莉 90 2
4 李四 90 2
5 张三 50 5
drop table Scores
[解决办法]
--try
select *,[排名]=(select count(*)+1 from Scores where tmp.Score <Score) from Scores tmp
[解决办法]
表jh03有下列数据:
name score
aa 99
bb 56
cc 56
dd 77
ee 78
ff 76
gg 78
ff 50
1. 名次生成方式1,Score重复时合并名次
SELECT * , Place=(SELECT COUNT(DISTINCT Score) FROM jh03 WHERE Score > = a.Score)
FROM jh03 a
ORDER BY Place
结果
Name Score Place
---------------- ----------------- -----------
aa 99.00 1
ee 78.00 2
gg 78.00 2
dd 77.00 3
ff 76.00 4
bb 56.00 5
cc 56.00 5
ff 50.00 6
2. 名次生成方式2 , Score重复时保留名次空缺
SELECT * , Place=(SELECT COUNT(Score) FROM jh03 WHERE Score > a.Score) + 1
FROM jh03 a
ORDER BY Place
结果
Name Score Place
--------------- ----------------- -----------
aa 99.00 1
ee 78.00 2
gg 78.00 2
dd 77.00 4
ff 76.00 5
bb 56.00 6
cc 56.00 6
ff 50.00 8