sql 查詢排列第幾

2021-04-13 11:11:59 字數 1800 閱讀 1829

create table ta(id **allint identity(1,1),name varchar(8),price int) --建表

insert into ta select 'a0',20 union all select 'a1',21 union all select 'a2',12 union all select 'a3',17 union all

select 'a4',22 union all select 'b1',33 union all select 'b3',14 union all select 'c2',46 union all select 'c3',32  --新增data

select * from ta --show data

create procedure t_proc --建儲存過程

@flag int

asif @flag=1

begin    --查詢出price最高的一條記錄(如46)

select top 1 * from ta order by price desc

endelse if @flag=2

begin    --查詢出price第二高的一條記錄(如33)

select top 1 * from ta where id not in(select top 1 id from ta order by price desc) order by price desc

endelse if @flag=3

begin    --查詢出price排名在第三到第六的記錄

select top 4 * from ta where id not in(select top 2 id from ta order by price desc) order by price desc

endelse if @flag=4

begin --查詢出price排名在第七到第九的記錄

select top 3 * from ta where id not in(select top 6 id from ta order by price desc) order by price desc

endgo

exec t_proc 1 --執行

/*----result (結果)

8c246

*/exec t_proc 2

/*----result

6b133

*/exec t_proc 3

/*----result

9c332

5a422

2a121

1a020

*/exec t_proc 4

/*----result

4a317

7b314

3a212

*/答者:hopewell_go(好的在後頭﹗希望更好﹗﹗) 信譽:100 級別:user2 日期:2006-11-18 8:49:03 id:37894036

id  name price

1 a0 20

2 a1 21

3 a2 12

4 a3 17

5 a4 22

6 b1 33

7 b3 14

8 c2 46

9 c3 32

select *,identity(int,1,1) tid into #table from tablename

order by price

select * from #table這樣的虛擬表可以實現你的要求

sql 返回 第幾周

孕婦預產期 週數 物件 userdefinedfunction dbo f crm getedcweek 指令碼日期 07 27 2020 17 24 52 set ansi nulls on goset quoted identifier on goalter function dbo f crm...

mysql查詢第幾行到第幾行記錄

1 查詢第一行記錄 select from table limit 1 2 查詢第n行到第m行記錄 select from table1 limit n 1,m n select from table limit 5,10 返回第6行到第15行的記錄 select from employee lim...

sql獲取最大 最小 第幾大 第幾小的數

表的例子結構 tbltest4 id 2312 3456 78955 76 1 選取最大的數 select max id from tbltest4 2 選取最大的三個數 select top 3 from tbltest4 order by id desc 3 選取第2大的數 select top...