SQL:Over 与 rank(),dense_rank(),row_number()
RANK ( ) OVER ( [query_partition_clause] order_by_clause ) over不能单独使用,要和分析函数:rank(),dense_rank(),row_number()等一起使用。
以下是个人见解: sql中的over函数和row_numbert()函数配合使用,可生成行号。可对某一列的值进行排序,对于相同值的数据行进行分组排序。如下表:
执行语句:select row_number() over(order by AID DESC) as rowid,* from bb后的结果如下: rowid标识行号有了,同时AID也按降序排列。AID有重复的记录,如果要删除rowid为2所对应的记录则可以: with [a] as (select row_number() over(order by AID desc) as rowid,* from bb) delete from [a] where rowid=2 如果查看rowid 为5所对应的记录的信息,可以: with [b] as (select row_number() over(order by AID desc) as rowid,* from bb) select * from [b] where rowid=5 注意: over里的order只能查查询里的原始数据进行操作,不会对计算出的新值或新字段起作用。 msdn中的说法如下: <ORDER BY 子句> 只能引用通过 FROM 子句可用的列。<ORDER BY 子句>不能与聚合窗口函数一起使用。
一个SQL2005分页的存储过程例子: set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON go ALTER PROCEDURE [dbo].[P_GetPagedOrders2005] (@startIndex INT, @endindex INT ) AS begin WITH orderList AS ( SELECT ROW_NUMBER() OVER (ORDER BY O.orderid DESC)AS Row, O.orderid,O.orderdate,O.customerid,C.CompanyName,E.FirstName+' '+E.LastName as EmployeeName from orders O left outer join Customers C on O.CustomerID=C.CustomerID left outer join Employees E on O.EmployeeID=E.EmployeeID) SELECT orderid,orderdate,customerid,companyName,employeeName FROM orderlist WHERE Row between @startIndex and @endIndex end |