难! 怎样得到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
(select top n 列名 '
from 表
order by 列名 ' )
列名和列名 '可以相同,看你用需要返回的列排序还是其他列排序了
[解决办法]
两种方法
一、直接新建个临时表
二、采用top,然后用not in去出重复的方法
[解决办法]
如果你经常使用的话,加一列比较好.
不经常使用的话,用select top 上面举的方法挺好.
临时表也不错(数据量不大的话).