22,210
社区成员
发帖
与我相关
我的任务
分享
create table a(id int,name varchar(10),grade int)
insert into a
select 1, 'a', 90 union all
select 2, 'b', 85 union all
select 3, 'c', 90
go
select * ,rank=rank() over(order by grade desc) from a
--不好意思,笔误了
create table student
(
id int,
name varchar(10),
grade int
)
insert into student select 1, 'a', 90
insert into student select 2, 'b', 85
insert into student select 3, 'c', 90
select *,rank = (select count(1)+ 1 from student where grade > a.grade)
from student a
order by rank
/*
id name grade rank
----------- ---------- ----------- -----------
1 a 90 1
3 c 90 1
2 b 85 3
(3 行受影响)
*/
--> 测试数据: #student
if object_id('tempdb.dbo.#student') is not null drop table #student
go
create table #student (id int,name varchar(1),grade int)
insert into #student
select 1,'a',90 union all
select 2,'b',85 union all
select 3,'c',90
-- 2005
select *,rank= rank()over(order by grade desc) from #student
--2000
select *,rank=(select count(*)+1 from #student where grade>t.grade)
from #student t
order by rank
id name grade rank
----------- ---- ----------- --------------------
1 a 90 1
3 c 90 1
2 b 85 3
create table student(id int,name varchar(10),grade int)
insert into student values(1 ,'a', 90)
insert into student values(2 ,'b', 85)
insert into student values(3 ,'c', 90)
go
select t.* , (select count(grade) from student where grade > t.grade) + 1 rank from student t
order by rank , id
drop table student
/*
id name grade rank
----------- ---------- ----------- -----------
1 a 90 1
3 c 90 1
2 b 85 3
(所影响的行数为 3 行)
*/
create table student(id int,name varchar(10),grade int)
insert into student values(1 ,'a', 90)
insert into student values(2 ,'b', 85)
insert into student values(3 ,'c', 90)
go
select t.* , RANK() over(order by grade desc) rank from student t
order by rank , id
drop table student
/*
id name grade rank
----------- ---------- ----------- --------------------
1 a 90 1
3 c 90 1
2 b 85 3
(3 行受影响)
*/
select *,rank=(selct count(1)+1 from tb a where a.name=tb.name and a.grade>=tb.grade) from tb
select *,rank = (select count(1)+ 1 from student where id = a.id and grade > a.grade)
from student a
select *,rank=row_number()over(order by grade desc) from tb