共享网

sql 取中间几条记录(select top 表达式)
2010-2-18 8:54:50 文章来源: 文章作者: 点击率:
核心提示: --从Table 表中取出第 m 条到第 n 条的记录:(Not In 版本) 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

--从Table 表中取出第 m 条到第 n 条的记录:(Not In 版本)
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


   AS

declare @m int
declare @n int
declare @i int
declare @j int
set @m=12
set @n=8

set @i=@m-@n+1
set @j=@n-1
select @i,@j


exec('select top '+@i+' * from newsinfo where (id not in (select top '+@j+' id from newsinfo))')
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
 

欢迎访问编程之路,请在评论时遵守国家相关法律法规。评论不代表本站观点

  • 访客名称:

2010 编程之路 www.chr114.com All Rights Reserved