sql 查询排列第几

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这样的虚拟表可以实现你的要求
 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
SQL调优是提高数据库性能的一个重要方面,以下是一些SQL调优的技巧: 1. 使用索引:索引可以提高SQL查询的速度,因为它们使数据库可以更快地查找数据。确保表中的每个列都有适当的索引,特别是常用于WHERE和JOIN子句的列。 2. 优化查询语句:尽量避免在查询中使用通配符(如“%”),这会使查询变慢。还可以使用EXPLAIN命令来分析查询语句的性能,并找到需要优化的地方。 3. 缩小查询范围:尽量缩小查询范围,只检索需要的数据。例如,使用WHERE子句限制返回的行数。 4. 使用连接(JOIN):JOIN是一种将两个或多个表中的数据组合起来的方法。它可以提高查询的速度,但也可能会使查询变慢。因此,在使用JOIN时要注意优化查询。 5. 避免使用子查询:尽量避免使用子查询,因为它们会使查询变慢。如果一定要使用子查询,可以尝试使用嵌套查询或JOIN来提高性能。 6. 定期清理数据:定期清理不必要的数据,可以提高查询性能。例如,删除不再需要的数据或归档旧数据。 7. 使用合适的数据类型:选择合适的数据类型可以提高查询的速度。例如,使用整数而不是字符类型存储数字可以提高查询性能。 8. 使用批处理操作:尽可能使用批处理操作,以减少与数据库的交互次数,从而提高查询性能。 9. 避免在数据库中进行计算:尽量避免在数据库中进行计算,因为这会降低查询性能。最好在应用程序中进行计算,并将结果存储在数据库中。 以上是一些常见的SQL调优技巧,具体的优化方法需要根据具体的情况来决定。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值