读书人

求一条排序的sql语句,该如何解决

发布时间: 2012-01-28 22:06:13 作者: rapoo

求一条排序的sql语句
table f 包括两个字段
A B
a1 100
a2 99
a3 80
a4 90
a5 79
a6 79
a7 79
a8 70
求一条语句执行结果为:

a1 100
a2 99
a4 90
a3 80
a5 79
a6 79
a7 79

即取前5名,第5名如果分数相同则全部取上。


[解决办法]
create table t(A varchar(10),B int)
insert t select 'a1 ',100
union all select 'a2 ',99
union all select 'a3 ',80
union all select 'a4 ',90
union all select 'a5 ',79
union all select 'a6 ',79
union all select 'a7 ',79
union all select 'a8 ',70


select A,B from
(
select top 100 percent *,名次=(select count(1)+1 from t where B> a.B) from t a
order by 名次
)a
where 名次 <=5

A B
---------- -----------
a1 100
a2 99
a4 90
a3 80
a5 79
a6 79
a7 79

读书人网 >SQL Server

热点推荐