SQL 读取不连续的第30到40之间的数据

有时在读取数据时,会从数据库中读取从某个位置到某个位置的数据,但是这个ID已经被破坏,不连续时主要采用row_number()函数。。。

 

方法一:

select row_num,* from
(
 select *, row_number() over (order by I_VoucherMaterialID) as row_num from dbo.I_VoucherMaterial
) tt
where row_num between 30 and 40

注释:row_number()函数必须要接一个over对它排序。

 

方法二:

WITH OrderedOrders AS
(
     SELECT SalesOrderID, OrderDate,
     ROW_NUMBER() OVER (order by OrderDate)as RowNumber
     FROM Sales.SalesOrderHeader
)
SELECT *
FROM OrderedOrders
WHERE RowNumber between 30 and 40;

 

注释:指定临时命名的结果集,这些结果集称为公用表表达式 (CTE)。该表达式源自简单查询,并且在 SELECT、INSERT、UPDATE 或 DELETE 语句的执行范围内定义。该子句也可用在 CREATE VIEW 语句中,作为该语句的 SELECT 定义语句的一部分。公用表表达式可以包括对自身的引用。这种表达式称为递归公用表表达式。

格式:with Cust as
(
 select * from Employee
)
select * from Cust

方法三:
select * from
(select top 40 * from I_VoucherMaterial order by I_VoucherMaterialID) a
where I_VoucherMaterialID not in
(select top 30 I_VoucherMaterialID from I_VoucherMaterial order by I_VoucherMaterialID)

posted @ 2010-12-02 11:43  CIWang  阅读(564)  评论(1编辑  收藏  举报