需求描述:
成绩表 编号 姓名 成绩
1 张三 90
2 李四 85
3 王五 100
4 赵六 85
5 汪一 100
6 周九 78
7 何二 56
要求:
排下名次,因为这里有同分,所以必然会出现并列名次。
并列成绩名次排名有两种方式,其一是这样:
A
名次 姓名 成绩
1 王五 100
1 汪一 100
3 张三 90
4 赵六 85
4 李四 85
6 周九 78
7 何二 56
第二种还是这样:
B
名次 姓名 成绩
1 王五 100
1 汪一 100
2 张三 90
3 赵六 85
3 李四 85
4 周九 78
5 何二 56
对于A方式,比较好办,以Access数据库为例(其他数据库语法大同小异,变化一下对应的即可),可以写成这样:
复制代码 代码示例:
SELECT e.place AS 名次, d.name AS 姓名, d.mark AS 成绩
FROM [select a.id,count(b.id)+1 as place from sc a left join sc b on a.mark < b.mark group by a.id]. AS e INNER JOIN sc AS d ON e.id = d.id;
同时A方式也可以写成这样,效果等同,比上面那句效率低点:
复制代码 代码示例:
SELECT e.place AS 名次, d.name AS 姓名, d.mark AS 成绩
FROM [select a.id,count(iif(b.id is null,null,b.id))+1 as place from sc a left join sc b on a.mark<b.mark group by a.id]. AS e INNER JOIN sc AS d ON e.id = d.id;
而B方式则有些麻烦,不过最终还是实现了:
复制代码 代码示例:
SELECT e.place AS 名次, d.name AS 姓名, d.mark AS 成绩
FROM [select c.id,count(iif(c.mark is null,null,c.mark))+1 as place from (select a.id,b.mark from sc a left join sc b on a.mark < b.mark group by a.id,b.mark)c group by c.id]. AS e INNER JOIN sc AS d ON e.id = d.id;