日期:2014-05-18  浏览次数:20376 次

求助:怎样查询指定第几条数据
一张表没有主键,也没有编号列,我就想按某个字段排序后查指定的行,如第3行.

table1:

Name                 Age
Allen               12
bill                 18
kate                 33
cystal             25
crane               35

我要查第2行的数据出来,按Age排序.
我写出一种:
select   top   1   *   from   (select   top   2   *   from   table1   order   by   age)   order   by   age   desc

如果table1很大的话,而且是取最后面的几条(select   top   2   *   from   table1   order   by   age)形成的临时表就会很大,效率就不高了.

有哪个大哥有更好的方法,小第只有30分了,不好意思

------解决方案--------------------
--用临时表吧

select id=identity(int,1,1),* into # from table1

select * from # where id between 开始值 and 结束值
------解决方案--------------------
05可以这样:
select *
from
(select *,row=row_number()over(order by age asc) from ta)ta
where row=2

2000:
--取最后两条,可生成临时表取其中一条
set rowcount 2
select * from ta order by age desc
set rowcount0
------解决方案--------------------
如果Age列不重复,则可以这样试试:
----创建测试数据
declare @t table(Name varchar(10),Age int)
insert @t
select 'Allen ', 12 union all
select 'bill ', 18 union all
select 'kate ', 33 union all
select 'cystal ', 25 union all
select 'crane ', 35

----查询(取Age第二小的行)
SELECT * FROM @t as a WHERE (select count(*) from @t where Age < a.Age) = 1

/*结果
Name Age
------------------
bill 18
*/