求一排名语句!
我有一张1000万条数据的表。格式如下:
CREATE TABLE [userinfo] (
[idx] [bigint] IDENTITY (1, 1) NOT NULL ,
[username] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
[password] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
[score] [int] NOT NULL ,
[lvl] [int] NOT NULL ,
[money] [int] NOT NULL ,
CONSTRAINT [PK_userinfo] PRIMARY KEY CLUSTERED
(
[idx]
) ON [PRIMARY]
) ON [PRIMARY]
GO
现在需要实时的计算某人的以score高低排序的前10名和后10名。
比如:输入 'mary ' ,立即计算出以score从高到低排序的在mary前10人和后10人的数据
username score
.....前10人.....
mary 100
.....后10人.....
万分感谢各位达人帮忙!!
------解决方案--------------------Select * From (
Select TOP 10 * From userinfo Where Score > (Select Score From userinfo Where username = 'mary ') Order By Score Desc) A
Union All
Select * From userinfo Where username = 'mary '
Union All
Select * From (
Select TOP 10 * From userinfo Where Score < (Select Score From userinfo Where username = 'mary ') Order By Score) B
------解决方案--------------------我的作法和 paoluo 一樣。不過在後面的10條數據以降序排列了一下。這樣要是數據多的話看起來會直觀些。
Select * from (
Select top 10 [username],[score] from userinfo
where score> ( Select score from userinfo where username= 'mary ' )
order by score desc ) A
union all
Select username, score from userinfo where username= 'mary '
union all
Select * from(
Select top 10 [username],[score] from userinfo
where score < ( Select score from userinfo where username= 'mary ' )
order by score asc )B
order by Score desc
------解决方案--------------------CREATE TABLE [userinfo] (
[idx] [bigint] IDENTITY (1, 1) NOT NULL ,
[username] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
[password] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
[score] [int] NOT NULL ,
[lvl] [int] NOT NULL ,
[money] [int] NOT NULL ,
CONSTRAINT [PK_userinfo] PRIMARY KEY CLUSTERED
(
[idx]
) ON [PRIMARY]
) ON [PRIMARY]
--插入测试49
declare @i int
set @i=1
while 50> @i
begin
insert userinfo(username,score,lvl,[money]) values( 'mary '+rtrim(@i),1,2,2)
set @i=@i+1
end
select * from userinfo--查询
update userinfo set username= 'mary ' where idx=30--更新第30条记录为mary
查询结果:
declare @username varchar(50)
set @username= 'mary '
select * from userinfo
where idx between --少了一个关键字
(select idx-10 from userinfo where username=@username)
and
(select idx+10 from userinfo where username=@username)
idx username password score lvl money
-------------------- -------------------------------------------------- -------------------------------------------------- ----------- ----------- -----------
20 mary20 NULL 1 2 2
21 mary21