Sqlserver查询数据第N条到第M条

--查询一个范围的数据有以下几种方式
1、select Top 10 * from tableA            --查询前10条
2、select Top 20 Percent * from tableA    --查询前20%条
--如果要查询后多少或者后百分之多少,只需要加上order by条件

--Where条件+比较符获取范围,例如:
select * from tableA where id > 10
-- >、>=、<、<= and or等等进行组合条件

--between n and m,取出第n条到第m条数据
select * from tableA where id between 10 an 25

--in、not in
select * from tableA where id in (1,2,3)
select * from tableA where id not in (1,2,3)

面试常考:取出某张表中 id 或 别的字段 第N条到第M条数据;
例如:有个学生表Student,有字段编号No,姓名Name,主键Id,要你取出学号在20到50的学生。

这个首先想到可能学号不连续并且没有排序等等,

解法:1、先查询表并按学生编号排序生成一个序号列serial
    select ROW_NUMBER()OVER(ORDER BY No) as serial,* from Student 
    2、使用嵌套查询,将上面查询结果作为子查询语句,最后使用between n and m,获取serial为20到50的学生
    select * from (
    select ROW_NUMBER()OVER(ORDER BY No) as serial,* from Student ) as a
    where a.serial between 20 and 50

  • 2
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值