ROW_NUMBER

The ROW_NUMBER ranking function gives numbers to every record in a dataset. So, when we need to sort records and add sorting numbers to the records, ROW_NUMBER does it for us. The ROW_NUMBER function, as with all other ranking functions, needs the OVER clause. The OVER clause declares sorted parts of records in a dataset called frames, and every ranking function works on every frame. The OVER clause has three parts:

  • PARTITION BY
  • ORDER BY
  • ROWS BETWEEN

The best way to show what every part of the OVER clause is dedicated to is to go through several examples. The following example shows the basics of how to use the ranking function. We have a set of products in a table called Production.Product in the AdventureWorks database. Within ...

Get Hands-On Data Science with SQL Server 2017 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.