我的答案: select * top 10 from (select * top 40 from a) order by id desc
不知哪里错了?或者各位有其它更好的方法麻烦指点一下吧。
...全文
34635打赏收藏
今天面试的一道题求解
今天面试,有道SQL题,到最后居然说我写错了,所以来这里求个解。 现有一数据表A,要求得到第31条至第40条的数据,表中ID字段为自动增长列,但有可能不连续。 我的答案: select * top 10 from (select * top 40 from a) order by id desc 不知哪里错了?或者各位有其它更好的方法麻烦指点一下吧。
我的答案: select * top 10 from (select * top 40 from a) order by id desc
------------------------
既然楼主说可能不连续,那么你怎么就知道 从第31条到第40条之间共 10条记录呢?
如果你肯定是10的话,那还要这样写吗?这样写不好吗 select * from t where id between 31 and 40
这个题本来就有问题,上面的回复都把 第31和第40条就当成 它的 id了,这个表id不连续可能是下面这种情况
id num
1 1
5 2
10 3
31 4
40 5
... ...
xx 31
... ...
yy 40
... ...
num是指第多个行。现在求取第5条到第8条记录
create table #(num int identity(1,1),id int)
insert into #
select 1 union all
select 5 union all
select 10 union all
select 30 union all
select 31 union all
select 35 union all
select 50 union all
select 60 union all
select 80
select id from # a
where exists(select 1 from # where id<=a.id having count(1) between 5 and 8)
/*
id
-----------
31
35
50
60
总结:
select top 10 * from tab
where id not in (select top 30 id from tab order by id)
order by id
select top m * from tablename where id not in (select top n-1 id from tablename)
WITH OrderById AS (SELECT *, ROW_NUMBER() OVER (ORDER BY [ID]) AS RowId FROM a )
SELECT * FROM OrderById WHERE RowId between 30 and 40;
环境:sql server 2005:
select * from (select row_number() over (order by id desc) num,* from a) as tb
where tb.num between 31 and 40
环境:sql server 2000:
declare @tb table(idx int identity(1,1),Id int)
insert @tb(id)
select id from a order by id desc
select a.* from a,@tb t
where a.id=t.id and t.idx between 31 and 40 order by t.idx