Pages

Men

rh

7/07/2012

ROW_NUMBER in SQL server

ROW_NUMBER
Returns the sequential number of a row within a partition of a result set, starting at 1 for the first row in each partition.

Example :

USE AdventureWorks2012;

GO
SELECT 
           ROW_NUMBER() OVER(ORDER BY SalesYTD DESC) AS Row,
           FirstName,
           LastName,
           ROUND(SalesYTD,2,1) AS "Sales YTD"
FROM 
           Sales.vSalesPerson
WHERE 
            TerritoryName IS NOT NULL AND SalesYTD <> 0;

Remarks:-

There is no guarantee that the rows returned by a query using ROW_NUMBER() will be ordered exactly the same with each execution unless the following conditions are true.
  1. Values of the partitioned column are unique.
  2. Values of the ORDER BY columns are unique.
  3. Combinations of values of the partition column and ORDER BY columns are unique.

No comments :

Post a Comment