语法:
ROW_NUMBER ( )
OVER ( [ <partition_by_clause> ] <order_by_clause> )
备注:
ORDER BY 子句可确定在特定分区中为行分配唯一 ROW_NUMBER 的顺序。
参数
<partition_by_clause>
将 FROM 子句生成的结果集划入应用了 ROW_NUMBER 函数的分区。
<order_by_clause>
确定将 ROW_NUMBER 值分配给分区中的行的顺序。有关详细信息,请参阅 ORDER BY 子句 (Transact-SQL)。
有关详细信息,请参阅 OVER 子句 (Transact-SQL)。
例子
一、以下示例将根据年初至今的销售额,返回 AdventureWorks 中销售人员的 ROW_NUMBER。
USE AdventureWorks
GO
SELECT c.FirstName, c.LastName, ROW_NUMBER() OVER(ORDER BY SalesYTD DESC) AS 'Row Number', s.SalesYTD, a.PostalCode
FROM Sales.SalesPerson s JOIN Person.Contact c on s.SalesPersonID = c.ContactID
JOIN Person.Address a ON a.AddressID = c.ContactID
WHERE TerritoryID IS NOT NULL AND SalesYTD <> 0
二、以下示例将返回行号为 50 到 60(含)的行,并以 OrderDate 排序。
USE AdventureWorks;
GO
WITH OrderedOrders AS
(SELECT SalesOrderID, OrderDate,
ROW_NUMBER() OVER (order by OrderDate)as RowNumber
FROM Sales.SalesOrderHeader )
SELECT *
FROM OrderedOrders
WHERE RowNumber between 50 and 60;
三、实现分页存储过程(固定到某个表的数据)
SET
ANSI_NULLS
ON
GO
SET
QUOTED_IDENTIFIER
ON
GO
-- =============================================
-- Author: cxw
-- Create date: 2006/11/14
-- Description:
利用
Row_Number
函数实现分页存储过程
-- exec DividePageForROW_NUMBER 2,1,'',''
-- =============================================
Create
PROCEDURE
DividePageForROW_NUMBER
@iPageSize
int
--
每页数
,
@iIndexPage
int
--
第几页
,
@vOrderBy
varchar
(
50
)
--
排序字段
,
@iRowCount
int
--
总记录数
AS
BEGIN
SET
NOCOUNT
ON
;
with
PageTable
as
(
select
row_number
()
over
(
order
by
ReasonID
)
TID
,*
from
A
)
select
*
from
PageTable
where
TID
between
((
@iIndexPage
-
1
)*
@iPageSize
+
1
)
and
@iPageSize
*
@iIndexPage
SET
NOCOUNT
OFF
;
END
GO