sql 取中间几条记录(select top 表达式)
1个回答
展开全部
SELECT TOP n-m+1 * FROM Table WHERE (id NOT IN (SELECT TOP m-1 id FROM Table )) --从TABLE表中取出第m到n条记录 (Exists版本)
SELECT TOP n-m+1 * FROM TABLE AS a WHERE Not Exists
(Select * From (Select Top m-1 * From TABLE order by id) b Where b.id=a.id )
Order by id--m为上标,n为下标,例如取出第8到12条记录,m=8,n=12,Table为表名
Select Top n-m+1 * From Table
Where Id>(Select Max(Id) From
(Select Top m-1 Id From Table Order By Id Asc) Temp)分析:--查询从第M条至N条的记录,写到存储过程中就是输入参数 declare @m int-- declare @n int-- declare @x int declare @y int--设置测试值 set @m=3 set @n=10 set @x=(@n-@m+1) set @y=(@m-1)/* 语法 Select top (n-(m-1)) * from [表名] where [parimary key] not in(select top (m-1) [主键] from [表名] order by [排序字段及排序方法]) order by [排序字段及排序方法 ]; */--测试用例,因为T-sql top 后不支持表达式,故采取下面的方法 exec('select top '+@x+'* from kf.T_Community where [C_ID] not in (select top '+@y+' [C_ID] from kf.T_Community order by [C_ID]) order by [C_ID]')--PS:如果在Orcale中,可以直接通过rownumber来控制,这样就容易多了例子:CREATE PROCEDURE TopNM ASdeclare @m int
declare @n int
declare @i int
declare @j intset @m=12set @n=8set @i=@m-@n+1
set @j=@n-1
GO或者(格式:Select top (n-(m-1)) * from [表名] where [parimary key] not in(select top (m-1) [主键] from [表名] order by [排序字段及排序方法]) order by [排序字段及排序方法 ]; )select top 3 * from newsinfo where (id not in (select top 3 id from newsinfo order by id desc )) order by id desc
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询