鉴于以下表格内容:
StudentNum Score
1 100%
2 95%
3 99%
4 0%
5 12%
我如何获得"#2中的5个"对于StudentNum = 3。
我能想到的唯一方法就是在应用程序代码中获取所有项目然后获取索引。例如:
items = SELECT StudentNum FROM table ORDER BY score DESC
student_3_position = items.index('3') + 1
total_positions = len(items)
'Student3 is #%s out of %s' % (student_3_position, total_positions)
有没有办法直接在SQL中执行此操作?
答案 0 :(得分:0)
准备数据:
create table dbo.temp (StudentNum int identity (1,1), Score int)
insert into dbo.temp values (100)
insert into dbo.temp values (95)
insert into dbo.temp values (99)
insert into dbo.temp values (12)
insert into dbo.temp values (0)
结果:
select *, ROW_NUMBER() OVER (ORDER BY Score desc) as 'Rank' from dbo.temp order by StudentNum