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

怎么取一个表记录中的第30~40条记录
请教:比如一个表有100条记录怎么取其中的第30至第40条记录??谢谢!

------解决方案--------------------
select top 10 * from (select top 40 * from table) t order by id desc
------解决方案--------------------

--第一种方法
--第11条到第20条,共选出10条记录
select *
from (select top 10 * from (select top 20 * from 表名 order by ID) t1 order by ID desc) t2
order by ID


--第二种方法
--第11条到第20条,共选出10条记录
select top 10 *
from 表名
where ID> (select max(ID) from (select top 10 ID from 表名 order by ID) t1)
order by ID


------解决方案--------------------
取n到m条记录的语句

1.
select top m * from tablename where id not in (select top n id from tablename)

2.
select top m * into 临时表(或表变量) from tablename order by columnname -- 将top m笔插入
set rowcount n
select * from 表变量 order by columnname desc

3.
select top n * from
(select top m * from tablename order by columnname) a
order by columnname desc


4.如果tablename里没有其他identity列,那么:
select identity(int) id0,* into #temp from tablename

取n到m条的语句为:
select * from #temp where id0 > =n and id0 <= m

如果你在执行select identity(int) id0,* into #temp from tablename这条语句的时候报错,那是因为你的DB中间的select into/bulkcopy属性没有打开要先执行:
exec sp_dboption 你的DB名字, 'select into/bulkcopy ',true


5.如果表里有identity属性,那么简单:
select * from tablename where identitycol between n and m


------解决方案--------------------
select tid=identity(int,1,1),a.* into #table from 表
select top 11 * from (select top 40 * from #table) t order by t.tid desc

------解决方案--------------------
为什么要用order by
------解决方案--------------------
用临时表做:为临时表增加个自动增长列rowCount
select identity(int,1,1) as rowCount,* into #temp from tablename

查询临时表30-40的记录

select * from #temp where rowCount between 30 and 40

------解决方案--------------------
2005 还可以用row_number() over(order by)
------解决方案--------------------
select top 11 * from table where id not in (select top 39 id from table )
------解决方案--------------------
select top 10 * from (selet top 40 * from table) order by id desc
------解决方案--------------------
select top 40 * from tablename where id not in (select top 30 id from tablename)
dawugui(潇洒老乌龟) 说的经典
通俗易懂,你学会了吗?
----------------------------
您确定? 求求你了.先运行一下再说吧.....

无论SQL好不好,至少应该得出肯定的正确结果才行吧.

SELECT TOP 10 *
FROM table
WHERE id NOT IN(
SELECT TOP 30 id
FROM table
ORDER BY id ASC)
ORDER BY id ASC
------解决方案--------------------
SELECT TOP 10 *
FROM table
WHERE id NOT IN(
SELECT TOP 30 id
FROM table
ORDER BY id ASC)
ORDER BY id ASC

------解决方案--------------------
select top 10 * from (select top 40 * from table) order by id desc
------解决方案--------------------
select top 10 * from '表名 ' where id not in (select top 30 from '表名 ' order by id asc) order by id asc