22,181
社区成员




create table [tb]([姓名] nvarchar(4),[分数] nvarchar(5),[职位] nvarchar(6))
insert [tb]
select N'张三',N'100分',N'技术员' union all
select N'李四',N'120分',N'管理员'
--sql 2005
select * , 排名 = row_number() over(order by 分数) from tb
drop table tb
/*
姓名 分数 职位 排名
---- ----- ------ --------------------
张三 100分 技术员 1
李四 120分 管理员 2
(2 行受影响)
*/
create table [tb]([姓名] nvarchar(4),[分数] nvarchar(5),[职位] nvarchar(6))
insert [tb]
select N'张三',N'100分',N'技术员' union all
select N'李四',N'120分',N'管理员'
--sql 2000
select * , 排名 = (select count(1) from tb where 分数 > t.分数) + 1 from tb t order by 排名
drop table tb
/*
姓名 分数 职位 排名
---- ----- ------ -----------
李四 120分 管理员 1
张三 100分 技术员 2
(所影响的行数为 2 行)
*/
declare @t table(姓名 varchar(10),分数 varchar(10),职位 varchar(10))
insert @t select '张三' , '100分' , '技术员'
union all select '李四' , '120分' , '管理员'
select *,排名=(select count(1) from @t where 分数>=t.分数) from @t t order by 分数 desc
姓名 分数 职位 排名
---------- ---------- ---------- -----------
李四 120分 管理员 1
张三 100分 技术员 2
(2 行受影响)
SELECT
*,
rnk=(SELECT COUNT(*)
FROM tb
WHERE CAST(LEFT(Score,CHARINDEX('分',Score)-1) AS INT)>
CAST(LEFT(A.Score,CHARINDEX('分',A.Score)-1) AS INT))
FROM tb AS A
IF NOT OBJECT_ID('TB') IS NULL DROP TABLE TB
GO
CREATE TABLE TB([姓名] NVARCHAR(2),[分数] NVARCHAR(4),[职务] NVARCHAR(3))
INSERT TB
SELECT N'张三',N'100分',N'技术员' UNION ALL
SELECT N'李四',N'120分',N'管理员'
GO
SELECT 姓名,分数,职务,排名=IDENTITY(INT,1,1) INTO #TB FROM TB ORDER BY 分数
SELECT * FROM #TB
DROP TABLE #TB
/*姓名 分数 职务 排名
---- ---- ---- -----------
张三 100分 技术员 1
李四 120分 管理员 2
(所影响的行数为 2 行)
*/
--sql 2000
select * , 排名 = (select count(1) from tb where 分数 > t.分数) + 1 from tb t
--sql 2005
select * , 排名 = row_number() over(order by 分数) from tb
---测试数据---
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([姓名] varchar(4),[分数] varchar(5),[职位] varchar(6))
insert [tb]
select '张三','100分','技术员' union all
select '李四','120分','管理员'
---查询---
select
*,
排名=(select count(1)+1 from tb where 分数>t.分数)
from tb t
order by 排名
---结果---
姓名 分数 职位 排名
---- ----- ------ -----------
李四 120分 管理员 1
张三 100分 技术员 2
(所影响的行数为 2 行)
select
*,
排名=(select count(*) from tb where 分数>=t.分数)
from tb t
select *,排名=(select count(1) from tb where 分数>=t.分数) from tb t order by 分数
select *,排名=(select count(1) from tb where 分数<=t.分数) from tb t order by 分数
selecct
*,
排名=(select count(1)+1 from tb where 分数>t.分数)
from tb t