sql 查询排列第几

本文介绍了一个SQL存储过程的创建及使用示例,演示了如何根据不同条件查询价格排名的记录。通过存储过程实现了灵活的数据检索。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

create table ta(id smallint 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
as
if @flag=1
begin    --查询出price最高的一条记录(如46)
select top 1 * from ta order by price desc
end
else 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
end
else 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
end
else 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
end
go

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这样的虚拟表可以实现你的要求
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值