在SQL中怎样查询一个表的第20条数据到30条数据
1、创建测试表,
create table test_order(id number , value varchar2(20));
2、插入测试数据
insert into test_order select 100+level as id, 'value_'||level from dual connect by level<=100;
commit;
3、查询表中全量数据,select t.* from test_order t;
4、编写sql,根据ID进行排序,查询第20条数据到30条数据;
select * from (select t.*, row_number() over(order by id) rn from test_order t )
where rn >= 20 and rn <= 30;
SqlServer查询操作步骤:
①先根据ID升序 查询前30条记录信息,再将查询的结果根据ID降序 查询前20条记录。
select *
from (select top 20 * from (select top 30 * from 表名 order by ID) t1 order by ID desc) t2
order by ID
②先将查询出前10条记录信息,然后将这10条信息从结果集中剔除掉。
select top 10 * from 表名 where id not in (select top 10 id from 表名 order by id asc) order by ID
③先查询出前10条记录最大的ID,然后再查询出>ID的前10条记录信息。
select top10 *
from 表名
where ID>(select max(ID) from (select top10 ID from 表名 order by ID) t1)
order by ID
④SqlServer2005后可以根据ROW_NUMBER查询。
select * from
(select *, ROW_NUMBER() OVER (order by ID) AS ROWNUM from 表) t
where ROWNUM between 21 and 30
您好:
SQL Server中可以使用以下语句:
SELECT TOP 10 列名
FROM 表名
WHERE 主键 NOT IN (SELECT TOP 20 主键 FROM 表名 WHERE 条件 ORDER BY 排序)
AND 条件
ORDER BY 排序