ROWNUMBER SQL code example

Example 1: ms sql row_number over partition

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

Example 2: create row number in sql

SELECT t.A, t.B, t.C, ROW_NUMBER() OVER (ORDER BY t.A) as newId
  FROM dbo.tableZ AS t
  ORDER BY t.A;

Example 3: sql rownum

Returns results where the row number meets the passed condition.
Example: Returns the top 10 countries from the countries table.
SELECT * FROM countries
WHERE ROWNUM <= 10;

Example 4: rownum in sql

SELECT ROWNUM, a.*
FROM (SELECT customers.*
      FROM customers
      WHERE customer_id > 4500
      ORDER BY last_name) a;

Tags:

Sql Example