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

难! 怎样得到SQL返回结果的第N行?
怎样得到SQL返回结果的第N行?
比如

SELECT   name   FROM   person
WHERE   name   IS   NOT   NULL

结果是:

zhao
qian
sun
li


我想返回这个结果的第2行和第3行,即:

qian
sun



------解决方案--------------------
SELECT identity(int) id,name into #t FROM person
WHERE name IS NOT NULL

select top 2 * from #t where id> 1
------解决方案--------------------
SELECT identity(1,1) id,name into #t FROM person
WHERE name IS NOT NULL

select * from #t where [id] between 2 and 3
------解决方案--------------------
top 2 ?
----------------------------
id> 1的头两条
------解决方案--------------------
如lianqizhi(油条豆腐脑)的
SELECT identity(int) id,name into #t FROM person
WHERE name IS NOT NULL

select top 2 * from #t where id> 1

要加一个自增字段上去~


------解决方案--------------------
--插入临时表
select name into #t from person
WHERE name IS NOT NULL
--给临时表添加id
alter table #t add id identity(1,1)

declare @i int,@k int
--@i 返回的开始行,@k返回的结束行
declare @sql varchar(8000)

set @i=20
set @k=30
SET @sql=isnull(@sql, ' ')+ 'select top '+cast(@k-@i as varchar(20))+ ' name from #t where id not in(select top '+cast(@i as varchar(20)) + ' id from #t) '
print @sql
exec(@sql)
------解决方案--------------------
select * from (select top 3 name from person) a
where name not in (select top 1 name from person)
------解决方案--------------------
select top 1 name from (
SELECT top 3 name FROM person
WHERE name IS NOT NULL
order by name desc)

------解决方案--------------------
楼主的是什么系统啊?
identity不支持?
------解决方案--------------------
select * from (select *, row_number() over(order by getdate()) rn from person) a where rn> =2 and rn <=3

------解决方案--------------------
1.要有主键
2.取到临时表中,同时增加自增列,这个自增列就是序号.

------解决方案--------------------
试试我的
declare @t table(A1 varchar(10),A2 int)
insert @t select 'a ',1
union all select 'b ',2
union all select 'c ',3
union all select 'd ',4
union all select 'f ',5

select * from @t a where (select count(*) from @t where a2 <=a.a2)> =2
and (select count(*) from @t where a2 <=a.a2) <=3


------解决方案--------------------
无需临时表,麻烦!
select top 2 name from person where id in(select id from person
WHERE name IS NOT NULL) order by id desc
------解决方案--------------------
select top (1) from b where
zhujian not in select top(n) from b
------解决方案--------------------
通用格式
返回从n行开始的m条记录
select top m 列名
from 表
where 列名 ' not in